对的未定义引用
undefined reference to
可能重复:
C++模板,未定义的引用
我有一个非常简单的程序,由三个文件组成,它从普通数组构建向量:
//create.hpp
#ifndef CREATE_HPP_
#define CREATE_HPP_
#include <vector>
using namespace std;
template<class T>
vector<T> create_list(T uarray[], size_t size);
#endif /* CREATE_HPP_ */
//create.cpp
#include "create.hpp"
template<class T>
vector<T> create_list(T uarray[], size_t size){
vector<T> ulist(uarray, uarray + size);
return ulist;
}
//main.cpp
#include <vector>
#include <iostream>
#include "create.hpp"
using namespace std;
int main(){
char temp[] = { '/', '>' };
vector<char> uvec = create_list<char>(temp, 2);
vector<char>::iterator iter=uvec.begin();
for(;iter != uvec.end();iter++){
cout<<*iter<<endl;
}
return 0;
}
构建过程如下:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o create.o create.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.cpp
g++ -o main.exe main.o create.o
在构建程序时,我得到了这个错误:
main.o: In function `main':
../main.cpp:18: undefined reference to `std::vector<char, std::allocator<char> > create_list<char>(char*, unsigned int)'
这个程序真的很简单。但是,编译成功通过,但链接失败。然后我把所有的代码移到一个文件中,一切都像一个符咒。有人能帮我弄清楚吗?
是。答案很复杂。这与模板在C++中的实际工作方式有关。
简言之:完整的模板定义必须在头文件中,或者您必须有一个明确的实例化(例如。http://msdn.microsoft.com/en-us/library/by56e477(v=vs.80(.aspx(。
长答案(原因(:模板不是可以编译成二进制(对象(的代码。它们仅仅是"创建代码的配方",代码只能在实例化过程中创建。这也是为什么模板使用不准确可能导致编译时间过长和二进制文件过大的原因。
您已经在单独的.cpp
文件中定义了模板。每个文件都是单独编译的。您的create.cpp
不包含任何正在运行的代码,因此它将被编译器丢弃。稍后,在链接阶段,当链接器尝试将main.cpp
的二进制文件与create_list
链接时,它在其他编译的对象中找不到它,因此会出现此错误。要解决这个问题,您需要在create.cpp
中至少实例化一次模板,或者在头文件中实现。
相关文章:
- 编译C++时未定义的引用
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 对 Scalar ::Scalar() 的未定义引用
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 对复制 CTOR 和 CTOR 的未定义引用
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 右值引用未定义的行为
- 对"vtable for DigitalClock"的未定义引用 - 未定义对"DigitalClock::staticMetaObject"的引用 - Qt
- 函数类型到函数类型的引用:未定义的引用
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确
- 从c++调用Fortran子程序,链接时引用未定义
- 枚举引用未定义,但位于包含的头文件中