This is a rather a problem from a convoluted situation. I have a static pointer sitting in one of my header files. Which is being included everywhere, this is why I put it as a static pointer. So that I can quickly initilize it in my main function so that other files can use it.
The problem is this, even after I initialize it and put stuff into it. Other files only find it NULL. It is like every file that includes the header with the static pointer makes a copy of it for itself and even when others initialize it, each file has their own separate copy. Negating ofcourse, the purpose of having a global variable.
How can I cope up with this?. Maybe I am understanding a static variable wrong, or maybe is it because its a pointer?
Should i be declaring it as: &variable = 5; or just as variable = 5; or &variable = (int)5?
That’s what
staticmeans when applied to a variable at namespace scope: the variable is given internal linkage, making it “local” to a given translation unit (source file).If you have a
staticvariable at namespace scope in a header file and you include that header file in multiple .cpp files, there will be multiple instances of that variable: one for each of the .cpp files that include the header file.If you want a global variable that is shared across multiple source files, you need to make it
extern. Declare the variable as extern in the header file, then define the extern variable in exactly one of your .cpp files.