出现LINK错误:C ++中的Extern.如何访问另一个文件B.CPP中的文件A.CPP中修改的变量的值 [英] 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

查看:172
本文介绍了出现LINK错误:C ++中的Extern.如何访问另一个文件B.CPP中的文件A.CPP中修改的变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++代码中,我想在文件"B"中使用变量"VarX",而实际上在另一个文件"A"中对其进行了修改. 所以我看了一下@以下链接&使用外部概念.

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.

如何使用extern在源文件之间共享变量?

错误LNK2005:已在中定义"unsigned int VarX"(?VarX @@ 3IA) ***.obj.

error LNK2005: "unsigned int VarX" (?VarX@@3IA) already defined in ***.obj.

我的情况如下:

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注意:在头文件File1.h中,除了Extern定义之外,还有许多其他结构定义以及其他定义.

有人可以帮我吗?我应如何读取在另一个文件File3.cpp中在File2.cpp中修改的VarX的值.

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.

推荐答案

问题不是可访问性,而是多重定义.错误消息非常清楚,您正在代码中的某个地方重新定义VarX.

The problem isn't accessibility, but a multiple definition. The error message is pretty clear, somewhere in the code you're redefining VarX.

常见原因可能是:

  • 无效的版本-编译前是否清理过该版本?
  • 您在某个地方(在标头或实现文件中)有多个unsigned int VarX = 101;unsigned int VarX;,而没有extern声明.
  • #include "File2.cpp"在代码中的某处,导致其被多次编译.
  • 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.

这篇关于出现LINK错误:C ++中的Extern.如何访问另一个文件B.CPP中的文件A.CPP中修改的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆