內general.h中如何避免鏈接錯誤
#ifndef GENERAL
#define GENERAL
namespace counternamespace{
int upperbound;
int lowerbound;
}
#endif
內Analyzer.h
#ifndef ANALYZER
#define ANALYZER
#include"General.h"
class Analyzer
{
public :
int var ;
int func();
};
#endif
內Test.h
#ifndef TEST
#define TEST
#include"Analyzer.h" //Error
class Test2
{
public:
Test2(void);
public:
~Test2(void);
};
#endif
在上面的代碼時,我不在Test.h
裏面加分析器一切正常。但添加後顯示以下鏈接器錯誤。
1>Test2.obj : error LNK2005: "int counternamespace::lowerbound" ([email protected]@@3HA) already defined in Analyzer.obj
2>Test2.obj : error LNK2005: "int counternamespace::upperbound" ([email protected]@@3HA) already defined in Analyzer.obj
我已經加入了#ifndef
/#endif
。那麼我在哪裏做錯了?任何人都可以讓我知道嗎?
:好的。留下Test2.h文件。 Analyzer.h內部也包含了一般的.h文件。因此,在這種情況下,由於分析器和通用轉換單元中的名稱空間定義,應該存在一些鏈接器錯誤。但它沒有顯示任何鏈接器錯誤。你能澄清一下嗎? – Kenta
@Learner你有Analyser.cpp和Test2.cpp,兩者都是不同的編譯單元。 –
我已在此解決方案中添加了詳細信息,並在我的答案中添加了解決方案。 –