I know that this program is not using the static variable in an appropriate way, but it shows how to reproduce a behavior I have seen :
Main.cpp :
int main(){
MyObject* p = new MyObject();
Header::i = 5;
printf("i %i\n", Header::i);
p->update();
return 0;
}
MyObject.cpp :
MyObject::MyObject(){
}
void MyObject::update(){
printf("i %i\n", Header::i);
}
Extern.h :
namespace Header {
static int i;
};
The output I get is :
i : 5
i : 0
Why don't I get 5
for both outputs ? Where does this 0
come from ?
Could you explain how static variables work ?
You have two variables i
because it has internal linkage. That means that each compilation unit where the corresponding header was included has its own object i and other compilation units know nothing about presnece of that object in this compilation unit.
If you will remove specifier
static
then the linker should issue a message that the variable is defined twice.The same effect can be achieved if to place a variable in an unnamed namespace in C++ 2011. For example instead of
you could write
In this case varaible i also has internal linkage. This is valid for C++ 2011.
Its better to declare your variable with
extern
in your header file to specify that it has an external linkage. Otherwise the above behavior will occur or potential compile or link problems can happen.The variable that is declared static only has scope in the file in which it is declared where as the variable declared without static can be accessed from other files using an extern declaration.
Static variables have internal linkage which effectively means they are local to the compilation unit. Since you have the static variable declared in a header included in 2 source files, you basically have 2 distinct variables: one
i
local toMyObject.cpp
and another, differenti
, local tomain.cpp
You should not put static valiables in header files. That leads to every cpp file that includes that header to have a copy of that static local to its compilation unit.
What you could do is extern storage specifier:
Header:
Cpp:
As an addition to the all the answers. WHY it happens, was already explained. However HOW to fix it, was suggested till now only by using static/extern approach. This is little bit C-like. Unles you don't have to use the header in C-part of the project with C-linkage, you could use C++.
So IF you have really to use something static in your code.
Either declare the variable as a member of a class:
header.h
main.cpp
any_code.cpp
Or use a singleton to avoid the explicit initialization
header.h
any_code.cpp