Getting LINK error : Extern in C++. How to access the value of a variable which is modified in File A.CPP in another file File B.CPP

荒凉一梦 提交于 2020-01-05 19:48:09

问题


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 a unsigned int VarX; somewhere (in a header or an implementation file), without an extern 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!