Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Header Causes Multiply Defined Symbol Error

Tags:

c++

header

linker

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?

like image 838
Greg Avatar asked Sep 26 '11 20:09

Greg


2 Answers

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.

like image 88
MSN Avatar answered Sep 28 '22 06:09

MSN


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";
like image 28
Itsik Avatar answered Sep 28 '22 07:09

Itsik