C++ 全局变量

标签 c++ windows linker global-variables

我有一个头文件global.h,我在其中声明了一些我打算在其他文件中使用的变量。

#ifndef GLOBAL_H_
#define GLOBAL_H_

#include <stdio.h>

typedef struct tag_KG_Data
{
   int nKGStationID;
   int nKGComPort;

 }GLOBAL_VAR;

 GLOBAL_VAR g_GlobalVar;

 BOOL b_newDataReady;
 BOOL b_startedSocketClient;



#endif

起初我只在文件 test1.cpp 中使用 extern GLOBAL_VAR g_GlobalVar; 声明了 GLOBAL_VAR g_GlobalVar,并且工作得很好。然后我声明了 2 个 BOOL 并在 test2.cpp 中使用了它们,但是我得到一个 error LNK2005: "struct tag_KG_Data g_GlobalVar"(?g_GlobalVar@@3Utag_KG_Data @@A) 已经在 test1.obj 中定义,对于我拥有的每个全局变量,我都会遇到类似的错误。问题是我不使用 test2.cpp 中的 GLOBAL_VAR g_GlobalVartest1.cpp< 中的任何 BOOL/.

最佳答案

这是因为您在 header 中定义全局变量,而您应该只声明它们。

在全局定义前添加 extern,并在单个 cpp 文件中创建定义。

在标题中:

// Declarations
extern GLOBAL_VAR g_GlobalVar;
extern BOOL b_newDataReady;
extern BOOL b_startedSocketClient;

在一个cpp文件中:

// Definitions
GLOBAL_VAR g_GlobalVar;
BOOL b_newDataReady;
BOOL b_startedSocketClient;

关于C++ 全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12338712/

相关文章:

c++ - 声明一个大小不变的数组 - 编译错误

c - Dll注入(inject)失败

windows - Windows 上的 Git checkout 和 reset 偶尔会显示随机文件已更改

c++ - 编译 C++ 程序时 VS 2013 中的链接时错误 - B. Stroustrup's PPP using C++ : Ch. 8 - Q1 Drill?

c++ - 将静态库封装在动态链接库 (DLL) 中

xcode - Swift Xcode6B3 - 字节交换 - undefined symbol "__OSSwapInt16"

c++ - 为什么 qi::skip 会因来自词法分析器的标记而失败?

c++ - 具有取消处理的 async_wait 处理程序类成员

c++ - 使用 gTest 测试多个模板函数

windows - 微软低功耗蓝牙广告