i have a header file global.h where i declare a few variables that i intend to use in other files.
#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;, and worked just fine. Then i declared the 2 BOOLs 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. The thing is that i don’t use GLOBAL_VAR g_GlobalVar in test2.cpp or any of the BOOLs in test1.cpp.
This is because you are defining the globals in the header, while you should be only declaring them.
Add
externin front of your global definitions, and create a definition in a single cpp file.In the header:
In a cpp file: