编译多个文件时出现奇怪的未定义引用错误 我试图编写一个玩具程序来锻炼C++,但是我得到了一个奇怪的未定义的参考错误,我无法解决。
我的代码由3个文件组成: ex13_6.h:编译多个文件时出现奇怪的未定义引用错误 我试图编写一个玩具程序来锻炼C++,但是我得到了一个奇怪的未定义的参考错误,我无法解决。,c++,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,
#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);
}
以下是错误消息:
/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
/tmp/ccRwO7Mf.o:在函数'main'中:
main.cpp:(.text+0x5a):对“void ex13\u 6::bubble\u sort(std::vector&)”的未定义引用
collect2:ld返回了1个退出状态
我真的很感激任何帮助 模板化函数定义应位于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;
}
}
}
}
}
#包括
命名空间ex13_6{
模板类Cmp{
公众:
静态int eq(ta,tb){返回a==b;}
静态int lt(ta,tb){返回a对于(int i=0;i将bubble\u sort
模板的实现移动到头文件中
模板不像java的泛型,所有的魔术都发生在C++编译时。为了使编译器为每个模板实例化生成代码,它必须是可见的,要做到这一点,它必须在头(或其他文件)中。并包含在使用它的每个翻译单元中。
您需要将模板实现放在头文件中
当实例化模板时,编译器需要“查看”实现,因此如果只包含头,则实现需要在那里
不要包含.cpp文件。您或者需要在ex13_6.cpp
中显式实例化模板,或者应该将模板函数的实现移动到头文件ex13_6.h
中。请参阅:谢谢@user315052。但是为什么我不能将通用模板函数定义放在ex13_6.cpp中?@user690421:可以,但是正如我解释的,你需要一个明确的实例化。参见引用的问题。@杰西德。谢谢。现在有道理。虽然这听起来像是一个不雅的C++特性。
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
#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;
}
}
}
}
}