![](/img/trans.png)
[英]How to access a variable which is declare in namespace into another cpp file
[英]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
在我的C ++代碼中,我想在文件“ B”中使用變量“ VarX”,而實際上在另一個文件“ A”中對其進行了修改。 所以我看了一下下面的鏈接並使用了extern概念。
錯誤LNK2005:***。obj中已經定義了“ unsigned int VarX”(?VarX @@ 3IA)。
我的情況如下:
File1.h
extern unsigned int VarX;
File2.cpp
#include File1.h
unsigned int VarX = 101;
File3.cpp
#include File1.h
unsigned int temp = VarX;
重要說明:在頭文件File1.h中,除了Extern定義之外,還有許多其他結構定義以及其他定義。
有人可以幫我嗎 我應如何讀取另一個文件File3.cpp中File2.cpp中修改的VarX值。
問題不是可訪問性,而是多重定義。 錯誤消息非常清楚,您在代碼中的某個地方重新定義了VarX
。
常見原因可能是:
unsigned int VarX = 101;
或未unsigned int VarX;
某個地方(在標頭或實現文件中),而無需extern
聲明。 #include "File2.cpp"
,導致其被多次編譯。 我敢打賭,第二種可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.