编译多个文件时出现奇怪的未定义引用错误
weird undefined reference error when compiling multiple files
我正试图编写一个玩具程序来练习c++,但是我得到了一个奇怪的未定义引用错误,我无法解决。
我的代码包含3个文件:
ex13_6.h:
#include<vector>
namespace ex13_6 {
template<class T> class Cmp {
public:
static int eq(T a, T b) {return a == b;}
static int lt(T a, T b) {return a < b;}
};
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v);
}
ex13_6.cpp
#include<vector>
#include"ex13_6.h"
namespace ex13_6 {
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
int s = v.size();
T swap;
for (int i=0; i<s; i++) {
for (int j=0; j<s; j++) {
if (C::lt(v.at(j), v.at(i))) {
swap = v.at(i);
v.at(i) = v.at(j);
v.at(j) = swap;
}
}
}
}
}
main.cpp:
#include"ex13_6.h"
#include<iostream>
#include<vector>
using namespace std;
using namespace ex13_6;
int main() {
// Sort using default comparison for int
vector<int> v_int;
for (int i=0; i<10; i++) {
v_int.push_back(10-i);
}
bubble_sort(v_int);
cout << "sort of int vector:n";
for (vector<int>::const_iterator it = v_int.begin(); it != v_int.end(); it++) {
cout << ' ' << *it;
}
cout << 'n';
}
我正在编译使用:
g++ main.cpp -o main -std=gnu++0x ex13_6.cpp
错误信息如下:
/tmp/ccRwO7Mf.o: In function `main':
main.cpp:(.text+0x5a): undefined reference to `void ex13_6::bubble_sort<int, ex13_6::Cmp<int> >(std::vector<int, std::allocator<int> >&)'
collect2: ld returned 1 exit status
我真的很感谢任何帮助! 将bubble_sort
模板的实现移到头文件中。
模板不像Java中的泛型,所有神奇的东西都发生在c++的编译时。为了让编译器为每个模板实例化生成代码,它必须是可见的,并且要做到这一点,它必须在头文件(或其他一些文件)中,并且包含在使用它的每个翻译单元中。
模板化的函数定义应该在ex13_6.h文件中:
#include<vector>
namespace ex13_6 {
template<class T> class Cmp {
public:
static int eq(T a, T b) {return a == b;}
static int lt(T a, T b) {return a < b;}
};
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
int s = v.size();
T swap;
for (int i=0; i<s; i++) {
for (int j=0; j<s; j++) {
if (C::lt(v.at(j), v.at(i))) {
swap = v.at(i);
v.at(i) = v.at(j);
v.at(j) = swap;
}
}
}
}
}
您需要将模板实现放在头文件中。
当实例化模板时,编译器需要"看到"实现,所以如果你只包含头文件,实现需要在那里。
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用