Consider the following header file example: shared_example.h
#ifndef SHARED_EX
#define SHARED_EX
const int Shared_Int = 1;
const char * Shared_CString = "This is a string";
#endif
The shared_example.h file is included in multiple compilation units, which leads the linker to (correctly) complain that:
error LNK2005: "char const * const Shared_CString" (?Shared_CString@@3PBDB) already defined in First_Compilation_Unit.obj
Removing the Shared_CString constant from this file eliminates the issue.
So, I have two questions.
First, why doesn’t the Shared_Int constant trigger the same issue?
Second, what is the appropriate way to allow separate compilation units to make use of the same constant string value?
The first declaration is of a constant integral value. In C++,
consthas internal linkage by default.The second declaration is of a pointer to
const char. That declaration is notconstitself, and has no other linkage specifiers, so it does not have internal linkage. If you changed the declaration toconst char * constit would then become a const pointer toconst charand have internal linkage.