关于个g++的问题

Shentar 2008-04-20 10:54:28
定义了一个类模板,把接口和实现分别放在两个文件中,分别是chain.h和chain.cpp,主函数在nl.cpp中。
chain.cpp和nl.cpp中都已经包含chain.h,不知道为什么连接时出现下面的错误:
[root@hust nl]# g++ -c chain.cpp
[root@hust nl]# ls
chain.cpp chain.h chain.o nl.cpp
[root@hust nl]# g++ -c nl.cpp
[root@hust nl]# g++ -o main chain.o nl.o
nl.o: In function `main':
nl.cpp:(.text+0xb7): undefined reference to `chain<int>::cn_insert(int, int const&)'
nl.cpp:(.text+0xd8): undefined reference to `chain<int>::cn_insert(int, int const&)'
nl.cpp:(.text+0xeb): undefined reference to `chain<int>::cn_output(std::basic_ostream<char, std::char_traits<char> >&) const'
nl.cpp:(.text+0x12f): undefined reference to `chain<int>::cn_insert(int, int const&)'
nl.cpp:(.text+0x153): undefined reference to `chain<int>::cn_output(std::basic_ostream<char, std::char_traits<char> >&) const'
nl.cpp:(.text+0x179): undefined reference to `chain<int>::~chain()'
nl.cpp:(.text+0x18c): undefined reference to `chain<int>::~chain()'
nl.cpp:(.text+0x19c): undefined reference to `chain<int>::~chain()'
nl.cpp:(.text+0x1af): undefined reference to `chain<int>::~chain()'
collect2: ld 返回 1
[root@hust nl]#

把类模板的接口和函数的定义放在一个文件中就没有问题,对模板不是很了解,
...全文
60 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzr001 2008-04-20
  • 打赏
  • 举报
回复
我也遇到过,应该是g++不支持模板分离编译,模板类定义与实现必须在同一文件。
Treazy 2008-04-20
  • 打赏
  • 举报
回复
你先把头文件放在放进去编译生成.o

如果最后连接.o还是连接出错的话

应该是你使用的版本不支持模板分离编译

只能使用包含编译,或者使用export再试试
  • 打赏
  • 举报
回复
g++不支持模板分离编译,你还是写到一个文件中吧

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧