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.
a.cpp
toextern const int n = 8;
AFAIKconst
impliesstatic
, although I don't really know. – Larriganextern const int n;
in a.h and include that in both cpp files. – Nebulousconst int
is the same as astatic const int
. This means that the value in a.cpp isn't visible outside that file, so b.cpp can't see it. – Nebulous