![](/img/trans.png)
[英]including header and .cpp files into main .cpp file LNK2005 error already defined in object
[英]error LNK2005: already defined on including a header file twice
我需要在Visual Studio項目中的多個cpp文件中編輯和訪問一些變量。 因此,我創建了一個帶有名稱空間的頭文件,其中包含我需要的所有變量,如下所示:
namespace windowdimension{
TCHAR openwindows[20][180];
int winnum = 0;
int windowleft = 0;
int windowright = 1360;
INT windowtop = 0;
INT windowbottom = 768;
LONG leftarray[20];
LONG rightarray[20];
LONG toparray[20];
LONG bottomarray[20];
}
但是,如果我#include
在兩個源文件這個頭文件,我得到並稱參數這個連接錯誤2005年在其他的obj已經定義。
在提到相同錯誤的其他問題時,我在這里知道
函數定義只能出現一次。 #包含您的.h文件的每個.cpp文件都會生成該函數的另一個副本。
但這也適用於名稱空間變量嗎? 如果是這樣,我們如何確保跨多個源文件訪問特定變量?
您永遠不要在頭文件中定義全局變量。
為了能夠共享,您需要在頭文件中聲明它們(使用extern
關鍵字),並在.cpp文件中僅定義一次。
當然,永遠不要忘記在每個頭文件中包含防護( #pragma once
是可移植的解決方案):
global.hpp
#pragma once
namespace global {
extern int variable;
}
global.cpp
namespace global {
int variable = 0;
}
無論如何,使用全局變量是非常糟糕的做法。
您可能忘記了添加include防護 :
#ifndef HEADER_H
#define HEADER_H
namespace something {
}
#endif
另一種選擇是在頭文件的最開始使用#pragma once
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.