对的未定义引用

undefined reference to

本文关键字:引用 未定义      更新时间:2023-10-16

可能重复:
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中至少实例化一次模板,或者在头文件中实现。