问题
IN my C++ code I want to make use of a variable "VarX" in a file "B" which is actually modified in another file "A". So I had a look @ the following link & used extern concept.
How do I use extern to share variables between source files?
error LNK2005: "unsigned int VarX" (?VarX@@3IA) already defined in ***.obj.
My scenario is as follows:
File1.h
extern unsigned int VarX;
File2.cpp
#include File1.h
unsigned int VarX = 101;
File3.cpp
#include File1.h
unsigned int temp = VarX;
IMP NOTE: In the header file File1.h there are many other structure definitions and also many othe rdefinitions apart from the Extern definition.
Can someone help me in this. How shall I read the Value of VarX which is modified in File2.cpp in another File File3.cpp.
回答1:
The problem isn't accessibility, but a multiple definition. The error message is pretty clear, somewhere in the code you're redefining VarX
.
Common causes can be:
- invalid build - have you cleaned the build before compiling?
- you have multiple
unsigned int VarX = 101;
or aunsigned int VarX;
somewhere (in a header or an implementation file), without anextern
declaration. - you
#include "File2.cpp"
somewhere in the code, causing it to be compiled multiple times.
My bet is on the second possiblity.
来源:https://stackoverflow.com/questions/10298041/getting-link-error-extern-in-c-how-to-access-the-value-of-a-variable-which