模板化功能被报告为“未定义参考".编译期间 [英] Templated function being reported as "undefined reference" during compilation

查看:94
本文介绍了模板化功能被报告为“未定义参考".编译期间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的文件:

-------- [c.hpp] --------

--------[ c.hpp ]--------

#ifndef _C
#define _C

#include<iostream>
class C
{
public:
    template<class CARTYPE> void call(CARTYPE& c);
};

#endif

-------- [c.cpp] --------

--------[ 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] --------

--------[ v.cpp ]--------

class Merc
{};

-------- [main.cpp] --------

--------[ main.cpp ]--------

#include "c.hpp"
#include "v.cpp"
//#include "c.cpp"

int main()
{
    Merc m; 
    C someCar;
    someCar.call(m);

}//main

我可以使用命令g ++ -c main.cpp和g ++ -c c.cpp等为上述所有文件生成".o"文件. 但是,当我尝试使用g ++ -o car"c.o main.o v.o"链接".o"文件时 我收到此错误:

I'm able to generate ".o" files for all the above files, with the command g++ -c main.cpp and g++ -c c.cpp and so on. But when I try linking the ".o" files with g++ -o car c.o main.o v.o I get this error:

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文件可能是一种不好的做法.我做错了吗?在创建单独的对象文件并链接它们时,有没有更好的方法来满足模板化声明? ps:我正在以更为复杂的类结构使用模板化函数.这里显示的只是一个小例子,目的是向您展示我所面临的错误类型.

The error goes away when I uncomment the line #include "c.cpp" in main.cpp, but I feel it may be bad practice to include the cpp file this way. Am I doing this wrong? Is there a better way to cater to templated declarations while creating separate object files and linking them? p.s: I'm using the templated function in a much more complex class structure. What is shown here is just a small example for the sake of showing you the kind of error I'm facing.

推荐答案

解决此问题的一种方法是

A way to solve this problem is to

a.从c.cpp中删除"#include"c.hpp"",并且

a. remove '#include "c.hpp"' from c.cpp AND

b.在"c.hpp"末尾添加"c.cpp"(听起来很奇怪的"#include"c.pp"")

b. include 'c.cpp' at the end of 'c.hpp' (strange sounding '#include "c.pp"')

通过这种方式,模板定义可用于每个包含'c.hpp'的翻译单元,而无需在每个.cpp文件中明确使用.这称为包含模型"

This way the template definitions are availabe to each translation unit that includes 'c.hpp' without explicitly doing so in each .cpp file. This is called the 'inclusion model'

这篇关于模板化功能被报告为“未定义参考".编译期间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆