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++ 全局变量声明
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
