namespaces in different file, preprocessor directives and static variables

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.
Declaring object in header is not good idea. This is not namespace error, its normal c/c++ link error.

Hope below will fix your issue,

in myClass.cpp, do like following
 
myClass myNameSpace::importantVal;


in myClass.h
1
2
3
namespace myNameSpace {
extern myClass importantVal;
}


Last edited on
thanks richardforc, I will give it a try later.
Why shouldn't I declare object in a header?
Which would be a better solution?
Moving the namespace in a .cpp file?
If so, how to guarantee access to the namespace from the other files?
Thanks for the help.
with more googling I finally figured out why richardforc solution is right.
I just add here another reference I found and that clarified to me what I was doing wrong.

http://stackoverflow.com/questions/6109224/c-namespace-member-access-in-different-files-how-to-how-namespace-std-imple
Topic archived. No new replies allowed.