Let’s assume that I have files a.cpp b.cpp and file c.h. Both of the cpp files include the c.h file. The header file contains a bunch of const int definitions and when I compile them I get no errors and yet I can access those const as if they were global variables. So the question, why don’t I get any compilation errors if I have multiple const definitions as well as these const int’s having global-like scope?
Share
This is because a
constdeclaration at namespace scope implies internal linkage. An object with internal linkage is only available within the translation unit in which it is defined. So in a sense, the oneconstobject you have inc.his actually two different objects, one internal toa.cppand one internal tob.cpp.In other words,
is equivalent to
while
is similar to
because non-
constdeclarations at namespace scope imply external linkage. (In this last case, they aren’t actually equivalent.extern, as well as explicitly specifying external linkage, produces a declaration, not a definition, of an object.)Note that this is specific to C++. In C,
constdoesn’t change the implied linkage. The reason for this is that the C++ committee wanted you to be able to writein a header. In C, that header included from multiple files would cause linker errors, because you’d be defining the same object multiple times.