LNK2005: "already defined error

I am trying to use a global variable from shared .cpp files. I have an init.h file like:

//init.h #ifndef init #define init int a = 3; #endif 

I have an init.cpp file like: //init.cpp #include init.h

Then, finally, the main.cpp file:

 //main.cpp #include "init.h" int main(void) { while(1) { } } 

After that, I get the error message:

 1>init.obj : error LNK2005: "int a" ( ?a@ @3HA) already defined in main.obj 1> ..deneme.exe : fatal error LNK1169: one or more multiply defined symbols found 

Why does my #infdef control not solve this problem ?. I also tried using #pragma once , but I got the same error. What is wrong with my code?

+3
source share
1 answer

You need to mark your variable as extern and define it only once in the implementation file.

Since the code is now, you break the rule of one definition . In this case, the included guards do not help, since all translation units that include this header override the variable.

What you really need:

 //init.h #ifndef init #define init extern int a; #endif 

and definition:

 //init.cpp #include "init.h" int a = 3; 

Also, think twice before using global variables . What are you really trying to achieve?

+9
source

Source: https://habr.com/ru/post/1468953/


All Articles