在使用template的同时将程序的实现分为源文件与头文件所产生的报错

最近心血来潮突然想试试clion,把之前的一个链表程序迁移过去总是报错,

关键的是这一句:

undefined reference to `mytest<int>::test(int)'collect2.exe: error: ld returned 1 exit status

具体如下:

一开始还以为是cmake哪里搞错了,查了很久资料也没找到问题,最后经测试问题出在template处

简而言之,一般情况下,使用template时代码实现应以内联形式在头文件实现,不能放在源文件实现,即类似以下这种结构

注意:这里只是说一般情况,即也有不在头文件实现的替代方案,但是这是最方便的方案!

百度了很久,最后还是Stack Overflow牛逼,一搜就搜出来了

这里放出两个回答链接,相信看了就懂c++ - Why can templates only be implemented in the header file? - Stack Overflowhttps://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file

Standard C++https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl

关键词:clion cmake template class 头文件 源文件 分离实现

undefined reference to / error: ld returned 1 exit status

(虽然好像与有些无关,但是为了让其他像我一样以为是cmake的问题的人搜到,还是这么写吧(doge))

posted @ 2022-06-19 17:04  Hello418  阅读(22)  评论(0编辑  收藏  举报