It's because const
implies internal linkage by default, so
your "definition" isn't visible outside of the translation unit
where it appears.
In this case, by far the best solution is to put the declaration
(extern int const n;
) in a header file, and include that in
both a.cpp
and b.cpp
. The linkage is determined by the
first declaration the compiler sees, so the later definition in
a.cpp
will have the correct (external) linkage.
Alternatively, you can force the linkage in the definition:
extern int const n = 8;
Despite the extern
, this is still a definition; anything with
an initializer outside of a class definition is a definition.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…