我想要做的只是在头文件中定义一个变量,并在两个不同的 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模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)