c++ - Strange behavior of static global variable -
i know program not using static variable in appropriate way, shows how reproduce behavior 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 : 5 : 0 why don't 5 both outputs ? 0come ? explain how static variables work ?
static variables have internal linkage means local compilation unit. since have static variable declared in header included in 2 source files, have 2 distinct variables: 1 i local myobject.cpp , another, different i, local main.cpp
Comments
Post a Comment