|
发表于 2019-11-22 17:43:00
|
显示全部楼层
是么?
你vscode是怎么配置的,用的什么编译器?
据我了解,.cpp文件在编译时应该是先生成.obj文件再进行连接的,如果生成文件时模板没有实例化,那么连接之后是会找不到相应代码的。
我想你是不是main.cpp里include了numbers.cpp?
测试代码:main.cpp:
- #include <iostream>
- #include "numbers.h"
- using namespace std;
- int main() {
- numbers<int> a = { 1,2,3,4,5,6 };
- auto b = a + 3;
- cout << b << endl;
- system("pause");
- }
复制代码
vscode 使用MinGW64编译:
- > Executing task: g++ '-g' 'e:\vscode source file\c++\Test Projection\main.cpp' '-std=c++14' '-o' 'main.exe' <
- C:\Users\ADMINI~1\AppData\Local\Temp\ccTiogBg.o: In function `main':
- e:/vscode source file/c++/Test Projection/main.cpp:7: undefined reference to `numbers<int>::numbers(std::initializer_list<int>)'
- e:/vscode source file/c++/Test Projection/main.cpp:8: undefined reference to `numbers<int>::operator+(int) const'
- C:\Users\ADMINI~1\AppData\Local\Temp\ccTiogBg.o: In function `operator<<(std::ostream&, numbers<int> const&)':
- e:/vscode source file/c++/Test Projection/numbers.h:34: undefined reference to `numbers<int>::size() const'
- e:/vscode source file/c++/Test Projection/numbers.h:37: undefined reference to `numbers<int>::operator[](unsigned long long) const'
- collect2.exe: error: ld returned 1 exit status
- 终端进程已终止,退出代码: 1
复制代码
使用vs2017编译,也是同样的问题:- 1>------ 已启动生成: 项目: Project1, 配置: Debug x64 ------
- 1>源1.cpp
- 1>源1.obj : error LNK2019: 无法解析的外部符号 "public: __cdecl numbers<int>::numbers<int>(class std::initializer_list<int>)" (??0?$numbers@H@@QEAA@V?$initializer_list@H@std@@@Z),该符号在函数 main 中被引用
- 1>源1.obj : error LNK2019: 无法解析的外部符号 "public: unsigned __int64 const __cdecl numbers<int>::size(void)const " (?size@?$numbers@H@@QEBA?B_KXZ),该符号在函数 "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class numbers<int> const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBV?$numbers@H@@@Z) 中被引用
- 1>源1.obj : error LNK2019: 无法解析的外部符号 "public: int & __cdecl numbers<int>::operator[](unsigned __int64)const " (??A?$numbers@H@@QEBAAEAH_K@Z),该符号在函数 "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class numbers<int> const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBV?$numbers@H@@@Z) 中被引用
- 1>源1.obj : error LNK2019: 无法解析的外部符号 "public: class numbers<int> __cdecl numbers<int>::operator+(int)const " (??H?$numbers@H@@QEBA?AV0@H@Z),该符号在函数 main 中被引用
- 1>C:\Users\Administrator\source\repos\Project1\x64\Debug\Project1.exe : fatal error LNK1120: 4 个无法解析的外部命令
- 1>已完成生成项目“Project1.vcxproj”的操作 - 失败。
复制代码
把numbers.cpp内的内容全部扔到numbers.h下后,两程序均输出
符合预期
|
|