C++ C++;包含正确防护的重复符号链接器错误?
我正在编写一个程序来测试具体的继承,尽管我无法解决Clang返回的重复符号链接器错误。我的理解是,重复符号总是由于不正确的包含/防护而导致的。我已经三次检查了我的include/guards,但没有发现任何错误。复制符号是否可能是包含防护装置以外的其他原因造成的?非常感谢,随着我编程技能的提高,我打算在这里经常做出贡献 hC++ C++;包含正确防护的重复符号链接器错误?,c++,include-guards,duplicate-symbol,C++,Include Guards,Duplicate Symbol,我正在编写一个程序来测试具体的继承,尽管我无法解决Clang返回的重复符号链接器错误。我的理解是,重复符号总是由于不正确的包含/防护而导致的。我已经三次检查了我的include/guards,但没有发现任何错误。复制符号是否可能是包含防护装置以外的其他原因造成的?非常感谢,随着我编程技能的提高,我打算在这里经常做出贡献 h \ifndef POINTARRAY\u H #定义点数组 #包括“array.h” 朱尔斯 { 命名空间容器 { 类PointArray:公共数组 { 公众: PointA
\ifndef POINTARRAY\u H
#定义点数组
#包括“array.h”
朱尔斯
{
命名空间容器
{
类PointArray:公共数组
{
公众:
PointArray();//默认构造函数
~PointArray();//析构函数
PointArray(const PointArray&p);//复制构造函数
PointArray(const int i);//带输入参数的构造函数
PointArray和运算符=(常量PointArray和源);//赋值运算符
double Length()const;//数组中点之间的长度
};
}
}
#ifndef点阵列
#包括“PointArray.cpp”
#恩迪夫
#恩迪夫
.cpp
\ifndef POINTARRAY\u CPP
#定义点数组
#包括“PointArray.h”
使用名称空间Jules::CAD;
朱尔斯
{
命名空间容器
{
PointArray::PointArray():Array()//默认构造函数
{
}
PointArray::~PointArray()//析构函数
{
}
PointArray::PointArray(const PointArray&p):数组(p)//复制构造函数
{
}
PointArray::PointArray(const int i):数组(i)//带输入参数的构造函数
{
}
PointArray&PointArray::operator=(常量PointArray&source)//赋值运算符
{
if(this==&source)
归还*这个;
PointArray::运算符=(源);
归还*这个;
}
双点数组::Length()常量
{
双长点=0;
对于(int i=0;i
更新:谢谢大家的帮助。我现在理解了这些机制。不要在标题中包含
cpp
文件。如果执行此操作,则包含标题的每个翻译单元最终都会得到类的定义,例如,PointArray
,从而导致链接器错误和多个定义
从标题中删除此内容
#ifndef POINTARRAY_CPP
#include "PointArray.cpp"
#endif
#endif
您正在
#将.cpp
文件包含在.h
中,这将导致.cpp
代码包含在使用.h
的每个文件中(因此会出现重复符号)。您还滥用了include-guard:只有头文件需要include-guard.cpp
文件不应该包含它们。由于模板的原因,我应该在.h中包含.cpp。指示中明确规定了这样做。但我仍然通过PointArray中的守卫调用.h。h@kits:您的PointArray
类不是模板。但是如果它是模板,那么防护是否正确?是吗?谢谢。包含防护与多个定义链接错误无关。(在到达链接阶段之前,可能会出现多个声明/定义编译错误,如果没有这些错误)
#ifndef POINTARRAY_CPP
#define POINTARRAY_CPP
#include "PointArray.h"
using namespace Jules::CAD;
namespace Jules
{
namespace Containers
{
PointArray::PointArray() : Array<Point>() //default constructor
{
}
PointArray::~PointArray() //destructor
{
}
PointArray::PointArray(const PointArray& p) : Array<Point>(p) //copy constructor
{
}
PointArray::PointArray(const int i) : Array<Point>(i) //constructor with input argument
{
}
PointArray& PointArray::operator = (const PointArray& source) //assignment operator
{
if (this == &source)
return *this;
PointArray::operator = (source);
return *this;
}
double PointArray::Length() const
{
double lengthOfPoints = 0;
for (int i = 0; i < Array::Size()-1; i++)
lengthOfPoints += (*this)[i].Distance((*this)[i+1]);
return lengthOfPoints;
}
}
}
#endif
#ifndef POINTARRAY_CPP
#include "PointArray.cpp"
#endif
#endif