我想要做的只是在头文件中定义一个变量,然后在两个不同的 cpp 文件中使用它,而无需在每次包含该标头时重新定义该变量。
这是我的尝试:
变量.h
#ifndef VARIABLES_H // header guards
#define VARIABLES_H
static bool bShouldRegister;
#endif
(我也尝试过
extern
但没有任何改变)
在 cpp 文件中,我给它一个值
::bShouldRegister = true
或 bShouldRegister = true;
在我的其他 cpp 文件中,我通过创建一个线程并在循环中检查其值来检查它的值(是的,我的线程函数运行良好)
while (true)
{
if (::bShouldRegister) // Or if (bShouldRegister)
{
MessageBox(NULL,"Value Changed","Done",MB_OK|MB_ICONINFORMATION);
}
Sleep(100);
}
是的,
MessageBox
永远不会出现(bShouldRegister
永远不会被设置为true:/)
您应该使用
extern
,否则每个翻译单元中的 bShouldRegister
变量可能具有不同的值。
将其放入头文件(.h)中:
extern bool bShouldRegister;
将其放入实现文件之一(.cpp)中:
bool bShouldRegister;
另一种更简单的方法是使用
inline
关键字。将变量放入头文件中,如下所示:
inline bool bShouldRegister;
如果您可以使用 C++17,请考虑使用内联变量:
// in a header file
inline bool bShouldRegister = true;
请参阅内联变量如何工作?了解更多信息。
一种更像 C++ 的方式 是使用类成员,在语法上由
static
关键字指示。类成员变量具有隐式 external
链接。
#ifndef VARIABLES_H
#define VARIABLES_H
class RegUtil {
public:
static bool bShouldRegister;
};
#endif
在你的一个cpp文件中(也许
variables.cpp
),你必须定义这个类成员:
#include "variables.h"
bool RegUtil::bShouldRegister;
您需要在其中一个模块中定义变量:
bool bShouldRegister;
然后在标题中声明它
extern
(不是static
!):
extern bool bShouldRegister;
这里需要在一个类中定义bool bShouldRegister。你的头文件应该像这样。
#ifndef VARIABLES_H // header guards
#define VARIABLES_H
class abc{
public:
bool bShouldRegister;
abc();
#endif
现在在 abc 类的构造函数中初始化 cpp 文件中的 bShouldRegister 变量,然后使用类的对象在第二个 cpp 文件中使用此变量。您将收到您的消息框。