C++ Global variable declaration(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 = 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++ 全局变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 全局变量声明
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
