内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,两者都是不同的编译单元。 –
我已在此解决方案中添加了详细信息,并在我的答案中添加了解决方案。 –