静态全局变量的奇怪行为 [英] Strange behavior of static global variable
问题描述
我知道该程序未以适当的方式使用静态变量,但是它显示了如何重现我所看到的行为:
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 :
主要.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;
};
我得到的输出是:
i : 5
i : 0
为什么不我两个输出都得到 5
吗? 0
来自何处?
您能解释一下静态变量的工作原理吗?
Why don't I get 5
for both outputs ? Where does this 0
come from ?
Could you explain how static variables work ?
推荐答案
静态变量具有内部链接,这实际上意味着它们在本地是局部的。编译单元。由于在包含在2个源文件中的标头中声明了静态变量,因此基本上有2个不同的变量:一个 i
局部于 MyObject.cpp
和另一个不同的 i
,位于$ main.cpp
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 to MyObject.cpp
and another, different i
, local to main.cpp
这篇关于静态全局变量的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!