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++, const
has internal linkage by default.
The second declaration is of a pointer to const char
. That declaration is not const
itself, and has no other linkage specifiers, so it does not have internal linkage. If you changed the declaration to const char * const
it would then become a const pointer to const char
and have internal linkage.
shared_example.h
#ifndef SHARED_EX
#define SHARED_EX
extern const int Shared_Int;
extern const char * Shared_CString;
#endif
shared_example.c
const int Shared_Int = 1;
const char * Shared_CString = "This is a string";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With