【发布时间】:2010-10-07 05:16:10
【问题描述】:
这些是我的文件:
--------[ c.hpp ]--------
#ifndef _C
#define _C
#include<iostream>
class C
{
public:
template<class CARTYPE> void call(CARTYPE& c);
};
#endif
--------[ c.cpp ]--------
#include "c.hpp"
template<class CARTYPE> void C::call(CARTYPE& c)
{
//make use of c somewhere here
std::cout<<"Car"<<std::endl;
}
--------[ v.cpp ]--------
class Merc
{};
--------[ main.cpp ]--------
#include "c.hpp"
#include "v.cpp"
//#include "c.cpp"
int main()
{
Merc m;
C someCar;
someCar.call(m);
}//main
我可以为上述所有文件生成“.o”文件,使用命令 g++ -c main.cpp 和 g++ -c c.cpp 等等。 但是当我尝试使用 g++ -o car c.o main.o v.o 链接“.o”文件时 我收到此错误:
main.o: In function `main':
main.cpp:(.text+0x17): undefined reference to `void C::call<Merc>(Merc&)'
collect2: ld returned 1 exit status
当我取消注释 main.cpp 中的 #include "c.cpp" 行时,错误消失了,但我觉得以这种方式包含 cpp 文件可能是不好的做法。我做错了吗?在创建单独的目标文件并链接它们时,是否有更好的方法来满足模板化声明? p.s:我在更复杂的类结构中使用模板化函数。此处显示的只是一个小示例,目的是向您展示我所面临的错误类型。
【问题讨论】:
-
@Pavel:您指出的解决方案正是我需要的解决方案。谢谢:)
标签: c++ templates makefile linker object-files