C ++全局变量声明 [英] C++ Global variable declaration
问题描述
我想要做的只是在头文件中定义一个变量,并在两个不同的cpp文件中使用它,而无需重新定义每次包含该标题的变量
这是我的尝试:
Variables.h
#ifndef VARIABLES_H //标题卫兵
#define VARIABLES_H
static bool bShouldRegister;
#endif
(我也试过extern但没有改变) p>
在cpp文件中,我给它一个值 :: bShouldRegister = true
或 bShouldRegister = true;
在我的另一个cpp文件中,我通过创建一个线程并检查其值循环检查它的值工作良好)
while(true)
{
if(:: bShouldRegister)//或if (bShouldRegister)
{
MessageBox(NULL,Value Changed,Done,MB_OK | MB_ICONINFORMATION);
}
睡眠(100);
}
是的,MessageBox从不出现(bShouldRegister永远不会成真: / p>
您必须使用 extern
,否则您有<$ c $
将此文件放在头文件(.h)中:
extern bool bShouldRegister;
一个实现文件(.cpp):
bool bShouldRegister;
What I want to do is just to define a variable in a header file and use it on two different cpp files without redefinition that variable each time I include that header
Here is how I tried :
Variables.h
#ifndef VARIABLES_H // header guards
#define VARIABLES_H
static bool bShouldRegister;
#endif
(I also tried extern but nothing changed)
And in a cpp file I give it a value ::bShouldRegister = true
or bShouldRegister = true;
In my another cpp file I check it's value by creating a thread and check its value in a loop (and yes my thread function works well)
while (true)
{
if (::bShouldRegister) // Or if (bShouldRegister)
{
MessageBox(NULL,"Value Changed","Done",MB_OK|MB_ICONINFORMATION);
}
Sleep(100);
}
And yes, that MessageBox never appears (bShouldRegister never gets true :/)
You must use extern
, otherwise you have separate bShouldRegister
in each translation unit with probably different values.
Put this in a header file (.h):
extern bool bShouldRegister;
Put this just in one of implementation files (.cpp):
bool bShouldRegister;
这篇关于C ++全局变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!