Greg
Greg

Reputation: 1500

Shared Header Causes Multiply Defined Symbol Error

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?

Upvotes: 10

Views: 3170

Answers (3)

long404
long404

Reputation: 1035

Making them static will solve the issue. You are not seeing the Shared_Int because you are not using it in more then one of the c modules that you compile.

Edit: My bad - what I say is valid for C. Didn't saw the c++ tag. Sorry

Upvotes: 1

Itsik
Itsik

Reputation: 3930

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";

Upvotes: 4

MSN
MSN

Reputation: 54584

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.

Upvotes: 17

Related Questions