[英]c++ global variables
i have a header file global.h
where i declare a few variables that i intend to use in other files. 我有一个头文件
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
At first i declared only GLOBAL_VAR g_GlobalVar
in file test1.cpp
with extern GLOBAL_VAR g_GlobalVar;
起初,我只声明
GLOBAL_VAR g_GlobalVar
文件test1.cpp
与extern GLOBAL_VAR g_GlobalVar;
, and worked just fine. ,工作得很好。 Then i declared the 2
BOOL
s and used them in test2.cpp
, but i get an error LNK2005: "struct tag_KG_Data g_GlobalVar" (?g_GlobalVar@@3Utag_KG_Data@@A) already defined in test1.obj
and for every global variable i have i get a similar error. 然后我声明了2个
BOOL
并在test2.cpp
使用它们,但我得到一个error LNK2005: "struct tag_KG_Data g_GlobalVar" (?g_GlobalVar@@3Utag_KG_Data@@A) already defined in test1.obj
并且我有每个全局变量我得到了类似的错误。 The thing is that i don't use GLOBAL_VAR g_GlobalVar
in test2.cpp
or any of the BOOL
s in test1.cpp
. 问题是,我不使用
GLOBAL_VAR g_GlobalVar
在test2.cpp
或任何BOOL
以s test1.cpp
。
This is because you are defining the globals in the header, while you should be only declaring them. 这是因为您在标题中定义了全局变量,而您应该只声明它们。
Add extern
in front of your global definitions, and create a definition in a single cpp file. 在全局定义前添加
extern
,并在单个cpp文件中创建定义。
In the header: 在标题中:
// Declarations
extern GLOBAL_VAR g_GlobalVar;
extern BOOL b_newDataReady;
extern BOOL b_startedSocketClient;
In a cpp file: 在cpp文件中:
// Definitions
GLOBAL_VAR g_GlobalVar;
BOOL b_newDataReady;
BOOL b_startedSocketClient;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.