問題描述
我想要做的只是在頭文件中定義一個變量,并在兩個不同的 cpp 文件中使用它,而無需在每次包含該頭文件時重新定義該變量
這是我嘗試的方法:
變量.h
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
(我也試過 extern 但沒有任何改變)
(I also tried extern but nothing changed)
在一個 cpp 文件中,我給它一個值 ::bShouldRegister = true
或 bShouldRegister = true;
And in a cpp file I give it a value ::bShouldRegister = true
or bShouldRegister = true;
在我的另一個 cpp 文件中,我通過創建一個線程并在循環中檢查它的值來檢查它的值(是的,我的線程功能運行良好)
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);
}
是的,MessageBox 永遠不會出現(bShouldRegister 永遠不會為真:/)
And yes, that MessageBox never appears (bShouldRegister never gets true :/)
推薦答案
必須使用 extern
,否則每個翻譯單元中的 bShouldRegister
變量可能不同值.
You must use extern
, otherwise you will have separated bShouldRegister
variables in each translation unit with probably different values.
把它放在一個頭文件(.h)中:
Put this in a header file (.h):
extern bool bShouldRegister;
把它放在一個實現文件 (.cpp) 中:
Put this in one of implementation files (.cpp):
bool bShouldRegister;
這篇關于C++ 全局變量聲明的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!