编译多个文件时出现奇怪的未定义引用错误

weird undefined reference error when compiling multiple files

本文关键字:未定义 引用 错误 文件 编译      更新时间:2023-10-16

我正试图编写一个玩具程序来练习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;
                }
            }
        }
    }
}

您需要将模板实现放在头文件中。

当实例化模板时,编译器需要"看到"实现,所以如果你只包含头文件,实现需要在那里。