g++和模板的链接器错误

Linker error with g++ and templates

本文关键字:链接 错误 g++      更新时间:2023-10-16

我正在做一个简单的程序,当我找不到编译它的方法时,我正在使用C++中的模板来实现一个带有一些数据类型的库。

代码为:

VectorT.cpp文件:

template <class T>
VectorT<T>::VectorT(){
  elementos = NULL;
  numElementos=0;
}

VectorT.h文件:

#ifndef __VectorT_h__
#define __VectorT_h__
template <class T>
class VectorT{
  private:
    T * elementos;
    int numElementos;
  public:
    VectorT();
};
#include "VectorT.tpp"
#endif

以及编译方式,带有错误:

g++ -c -o obj/VectorT.o src/VectorT.cpp -I include/VectorT.h 
g++: warning: src/VectorT.cpp: linker input file unused because linking not done

知道吗?非常感谢。

这个"代码"无法编译,因为它仍然不是一个完整的代码。

通过这种方式,您可以编写测试代码,并且只需要添加头文件。例如:g++-o bin/testVector src/testVector.cpp-I include/而且这个程序不用编译任何其他东西就可以工作!唯一的细节是头文件和cpp文件必须在/include文件夹中,"VectorT.tpp"和VectorT.h,头文件和模板的实现。