模板链接器错误的显式实例化

Explicit instanciation of template linker error

本文关键字:实例化 错误 链接      更新时间:2023-10-16

我正在寻求您的帮助,因为我正在使用模板,似乎我误解了什么。

这是我的代码:

阿尔布雷·

template<typename T>
class Arbre;
template<typename T>
class Noeud
{
    friend class Arbre<T>;
    public :
    Noeud();
    ~Noeud();
    T get_info()const;
    private :
    T info;
    Noeud<T> *fg, *fd;
};
template<typename T>
class Arbre
{
    public :
    //Constructors-------------------------------------------------------------
    Arbre();
    /*
      other function definitions
    */
}

arbre.tpp

#include "arbre.h"
template <typename T>
Noeud<T>::Noeud(){
    fg = fd = 0;
}
template <typename T>
Noeud<T>::~Noeud(){
}
template <typename T>
T Noeud<T>::get_info()const{
    return info;
}
template <typename T>
Arbre<T>::Arbre(){
    racine = 0;
}
/*
  other function implementations...
*/

main.cpp 包含 "arbre.h" 并创建一个这样的对象:

Arbre<int> a;

所以按照这篇关于显式实例化的文章:http://www.cplusplus.com/forum/articles/14272/

我在 arbre.tpp 的末尾添加了这 2 行:

template class Noeud<int>;
template class Arbre<int>;

这样链接器就可以在arbre.o中编译我的对象的int版本的代码,这样我就可以将实现(arbre.tpp(与标头(arbre.h(分开。我的代码使用隐式实例化(arbre.tpp 包含在 header.h 的末尾(,但我想将它们分开。

我想知道为什么链接失败:

g++ -o main.o -c main.cpp -Wall -g -std=c++11
g++ -o arbre.o -c arbre.tpp -Wall -g -std=c++11
g++: warning: arbre.tpp: linker input file unused because linking not done
g++ -o arbre.out main.o arbre.o 
g++: error: arbre.o: No such file or directory
Makefile:9: recipe for target 'arbre.out' failed
make: *** [arbre.out] Error 1

你有什么想法吗?我正在做与我链接的文章相同的事情,不是吗?

提前谢谢。

显式实例化定义是不够的。一般来说,编译器应该假定主模板定义是它所看到的全部。因此,这些专业化依赖于未定义的成员。

但是,存在显式实例化声明的概念。它告诉编译器在其他地方查找模板定义。只需在标题底部添加这两个:

extern template class Noeud<int>;
extern template class Arbre<int>;

由于您使用的是非标准扩展,.tpp ,您可能希望告诉编译器您正在使用C++代码,g++ -x c++

带有模板定义的文件不能单独编译和链接。 只需尝试以下方法:-

在main.ccp文件顶部包含"arbre.tpp",如头文件,并仅编译main.cpp文件并生成exe。

在你的主要.cpp

#include"arbre.tpp"
$g++ main.cpp -o test
$./test (to run the application)