Why does “extern const int n;” not work as expected?

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.

Leave a Comment