boom
boom

Reputation: 6166

Duplicate Symbol problem

I have a header file MyNameSpace.h where i use namespace as under:

namespace NameSpace1

{
string first = "First";
...
}

namespace NameSpace2

{
string top = "Top";
}

But when i use the namespace object in my other classes including the header file. I got Duplicate symbol error as NameSpace1::first. What exactly it means and how to resolve this solution.

Upvotes: 0

Views: 1785

Answers (3)

s_b
s_b

Reputation: 491

@reko_t: Inclusion guard does not help against multiple variable definition, as include guard only protects from multiple inclusion per single compilation unit (eg. a source file).

Isn't that actually preventing multiple definitions?

Upvotes: 0

reko_t
reko_t

Reputation: 56440

You shouldn't define globals in headers, you need to tell the compiler it's defined elsewhere with the extern keyword. Otherwise the compiler tries to define the variable in every source file that includes the header.

Eg. in MyNameSpace.h you do:

namespace NameSpace1 {
    extern std::string first;
}

Then you'll do this in MyNameSpace.cpp:

namespace NameSpace1 {
    std::string first = "First";
}

Upvotes: 15

Naveen
Naveen

Reputation: 73473

First of all there can not be a namespace object, you can not create an object out of a namespace. It is there only for name resolution. Regarding the multiple definition problem, you are most probably missing the include guard for the header file.

Upvotes: 0

Related Questions