C++模板不能分离式编译!!

来源:互联网 发布:淘宝双11战队 编辑:程序博客网 时间:2024/05/22 12:59

写这篇文章为了说明一点:“很多C++编译器,不支持模板分离式编译!!” 当然还要加上时间是2010年7月26日!!!

下面直接看测试结果:

文件:A.h

 

文件:A.cpp

 

文件:main.cpp

 

编译:g++ -o a A.cpp main.cpp

结果:

/tmp/ccU0I87L.o: In function `main':

main.cpp:(.text+0x11): undefined reference to `A<double>::A()'

main.cpp:(.text+0x1d): undefined reference to `A<double>::show()'

collect2: ld returned 1 exit status

 

错误提示表明在链接的时候出错!!

也就是说,单独编译各个编译单元时,没有问题,但是在链接的时候找不到自动生成的函数!

 

解决方案:

不要分离编译,直接把实现的代码也放到头文件中!

修改后的文件:A.h

 

编译:g++ -o a main.cpp

结果:成功!

 

看来现在的C++编译器还不算很完善!

 

相关文章:

http://blog.sina.com.cn/s/blog_46625a5f010000ld.html

http://langfangwangbin.blog.163.com/blog/static/1005436342010517442368/

http://www.dutor.net/index.php/2009/11/cpp-noisolate-compile/?replytocom=463