C++ 与 gcc 编译器的奇怪链接错误

Weird linking error in C++ with gcc compiler

我在尝试编译我的源代码时遇到了一个奇怪的链接问题。我在下面粘贴我的代码以获得更好的解释。

LinkedList.h

#ifndef _LINKED_LIST
#define _LINKED_LIST

#include <iostream>
#include "ListInterface.h"
#include "Node.h"
#include "PrecondViolatedExcep.h"

template<class ItemType>
class LinkedList : public ListInterface<ItemType>{............
//There is the some code here, but thats not the point so i don't

#include "LinkedList.cpp"
#endif

main.cpp

#include "LinkedList.h"

int main()
{
    LinkedList<int> list;
}

你可以看到在 LinkedList.h 头文件下,我在底部包含了这一行 #include "LinkedList.cpp

所以现在我可以像这样编译: g++ main.cpp -o main。这对我来说完全没有问题,程序可以正常工作。

但是当我删除 LinkedList.h 头文件底部的这一行 #include "LinkedList.cpp 时出现链接问题。我这样编译: g++ main.cpp LinkedList.cpp -o main。理论上这应该不是问题,我在其他项目中大部分时间都是这样做的。所以这个问题对我来说有点奇怪。谁能指出这是什么原因?

您可能没有在 LinkedList.cpp 中包含 LinkedList.h,因此当它自行编译时(不在 main.cpp 中),编译器会对定义的构造的声明做出一些假设在 main.cpp 和 LinkedList.h 的顶部。解决单独 LinkedList.cpp 的包含问题,这应该可以修复错误。

我假设错误发生是因为模板 class 的某些方法在 LinkedList.cpp 文件中被定义。请记住,C++ 为每个模板特化编译单独的代码。

main.cpp使用LinkedList<int>时,它的一些方法没有定义,所以链接器会抱怨它们丢失了。

制作模板时class,方法的所有主体也应该在头文件中。

拜托,read this,这似乎是你的问题。

您也可以在 LinkedList.cpp 文件的底部添加 template class LinkedList<int>;,这称为 explicit instantiation