我有一个头文件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_GlobalVar
或 test1.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/