I have the following structure and object of structure defined in the header file as below:
struct STConfigurationDetails
{
bool bAutoStart;
bool bAutoLog;
bool bAutoScan;
bool bAutoMount;
bool bAutoOpen;
bool bAutoDetectLast;
};
struct STConfigurationDetails g_objConfigurationDetails ;
In the header file I have both structure definition and structure instantiation which is using g_objConfigurationDetails. This works fine when I include the header file to another cpp file and call the method. But in the moment I added the header file to another cpp file I got the error:
Error 1 error LNK2005: "struct STConfigurationDetails g_objConfigurationDetails" (?g_objConfigurationDetails@@3USTConfigurationDetails@@A) already defined in NDSClientDlg.obj NDSConnectDlg.obj NDSClient
Error 2 fatal error LNK1169: one or more multiply defined symbols found d:\FromClearCase\Development_view\NDS_11152010\exe\Debug\NDSClient.exe 1 NDSClient
After searching few threads I found out I have to declare my object as static and it solved. But I want to know why was I getting multiple instance error while I was creating the instance only in the header file.
Is this because my Header File has a global variable and it is being included in multiple CPPs?
Adding
staticmight solve your linking problem, but gives you a much bigger problem. That variable is no longer global and has a different value in every CPP file that uses it. You need to declare it asexternin the header file and then declare it one more time in just one CPP file as is.When you use
staticit means the variable will be completely local to the current CPP file and will not be exposed to other files. That’s why the linker no longer cares if there is another static variable in another file that has the same name. They are not the same variable.If you want a truly global variable, it must be declared in exactly one CPP file and only its prototype (with
extern) should be in a header file that will be shared with other CPP files. It’s exactly like functions – declared in one file, prototyped for the rest. For functions, you simply don’t provide a body. For variables, you useextern.