c++ - undefined reference

标签 c++ linker-errors undefined-reference build-error

<分区>

Possible Duplicate:
C++ templates, undefined reference

我有一个非常简单的程序,由三个文件组成,它从普通数组构建 vector :

//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++ 中的实际工作方式有关。

简短回答:完整的模板定义必须在头文件中,或者您必须在 CPP 文件中为给定类型进行显式实例化(例如 http://msdn.microsoft.com/en-us/library/by56e477(v=vs.80).aspx)。

长答案(原因):模板不是可以编译成二进制(对象)的代码。它们只是“创建代码的配方”,代码只能在实例化过程中创建。这也是为什么不正确地使用模板可能会导致编译时间过长和二进制文件大于所需的原因。

关于c++ - undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14005060/

相关文章:

c++ - 程序中引发的访问冲突(段错误)

c++ - 重载函数

ios - clang : error: linker command failed with exit code 1, Xcode 链接器错误

c++ - 链接器错误 - 请帮助 : error LNK2001: unresolved external symbol

c++ - 我收到一个不存在的 undefined reference 错误

c++ - 链接 boost 库时出现另一个 "undefined reference"错误

c++ - 不止一个重载函数实例

c++ - 努力将 LPSTR 和字符串添加到 LPCTSTR

ios - 将静态库引入项目时 undefined symbol

c++ - 为什么模板只能在头文件中实现?