I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++.
I have two projects, one is a static library and second
The kind of behavior you describe seems more like a problem when you have a DLL, but you are saying that your library is static, which looks weird.
Anyway, take care with global variables in multiple libraries, if you have a shared code library (DLL) you'll get a value for each part. Check out this question, can be useful.
The problem is likely to be one of initialization order. When the program is linked, there are 2 places where globalWord
is used in initialization:
text
("string text = globalWord;
")globalWord
itselfUnfortunately, the C++ standard does not specify the order of initialization of globals that come from different modules. Something similar to Matt's answer of using a function or a simple class (a singleton, for example) to access the global value is the usual way of enforcing a particular initialization order.
The C++ FAQ talks about this a little - if you plan to modify globalWord
in your program, the situation is made a little more complex than they discuss because they don't seem to address setting the value hidden behind the "construct on first use" function. Typically something like that would require something like a singleton class.
Don't use global variables. Just don't. Much better, if you HAVE to have globally accessible data, is to use a global function which will return globalWord, like this:
std::string globalWord()
{
static std::string word("Hi Mom");
return word;
}
This saves you from initialization order issues (read Effective C++ item #4).
With the "extern" keyword, you're telling the compiler that the actual variable exists somewhere else. You should also create a variable with the same name without the extern, in one and only one place. Ordinarily you'll get an error from the linker if you define two of them, but if one's in the library and one's not it might not figure it out.
Edit: make sure global.cpp is only in the library or test program, not both.