C++ 全局变量声明

2021-12-13 00:00:00 variables global-variables c++


我想要做的只是在头文件中定义一个变量,并在两个不同的 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 = truebShouldRegister = 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;

相关文章