Hello, I'm new in this forum.
I was trying to understand the following behaviour under Visual Studio C++ 2008 express edition.
I have defined my own class (myClass) in myClass.hpp & myClass.cpp
I have create a namespace in MyNameSp.hpp with the following sintax
1 2 3 4 5 6 7
|
#ifndef myNameSpace_hpp
#define myNameSpace_hpp
namespace myNameSpace
{myClass importantVal;}
#endif
|
I need to know the value in (let's say) file1.cpp and file2.cpp.
If I include the "MyNameSp.hpp" at the beginning of those files, it compiles, but it won't link:
error LNK2005: "myClass myNameSpace::importantVal" (?ImportantVal@myNameSpace@@3HA) already defined in file1.obj.
(and some others errors; it might be slightly different, my output is in italian)
After many different tentatives I figured out that modifying the code in MyNameSp.hpp with
1 2
|
namespace myNameSpace
{static myClass importantVal;}
|
make it works (it both compiles and links).
And this is the behaviour I actually want (only one copy of importantVal should exist)
Side note: I have tried also with int, and I had the same problem.
my question is:
Shouldn't the preprocessor directive prevent a double definition of the namespace (as it does with classes)? What am I not understanding?
Since static variables must be initialized, where should I do that?
Will be automatically used the default constructor? (which is fine, for me)
Thanks in advance for your help.