tags:

views:

94

answers:

3

Hi, 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.

+13  A: 

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";
}
reko_t
Is external meant to be extern ?
DumbCoder
Yes, sorry; fixed.
reko_t
@reko_t Thanks for this suggestion...
iSight
A: 

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.

Naveen
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).
reko_t
@reko_t: If include guards are missing and same header file got included twice in a single translation unit, multiple redefinition error will come. Isn't it?
Naveen
Yeah, that's true, but only if the variable is not declared with `extern`, duplicate symbols with `extern` don't produce an error, even without an include guard.
reko_t
Yes, I agree that the `extern` is a better way to do it than using a global variable in a header file.
Naveen
A: 

@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?

s_b
Duplicate symbol definitions occur across different translation units. For example if you have `int foo = 10;` in foo.h (with include guards), and foo.h is included from a.cpp and b.cpp, you will get an error indicating that foo was defined more than once. The reason for this is that the pre-processor definitions are reset for each translation unit.
reko_t