此問題是在函數實例化的外部文件中定義的名稱空間中定義和聲明函數模板。這是我能想到的最小的可重複的例子。 4個文件如下:單獨文件中名稱空間中的函數模板編譯得很好,但鏈接器找不到它
在一個名爲命名空間中的函數模板聲明:
// bar.h
#include <algorithm>
namespace barspace {
template <typename Iter>
void DoSomething (Iter first, Iter last);
}
在一個單獨的文件中的函數模板定義:
// bar.cpp
#include "bar.h"
namespace barspace {
template <typename Iter>
void DoSomething (Iter first, Iter last) {
typedef typename std::iterator_traits<Iter>::value_type val_t;
std::sort (first, last);
}
} // namespace barspace
主程序
// foo.h
#include "bar.h"
#include <vector>
頭
最後,調用函數模板的主程序:
//foo.cpp
#include "foo.h"
int main() {
std::vector<double> v_d;
for (int i = 0; i < 10; i++) {
v_d.push_back (i);
}
barspace::DoSomething (v_d.begin(), v_d.end());
return 0;
}
我編譯如下:
g++ -c -o bar.o bar.cpp
g++ -c -o foo.o foo.cpp
這些運行正常。現在對於鏈接:
foo.o: In function `main':
foo.cpp:(.text+0x6e): undefined reference to `void barspace::DoSomething<__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > > >(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >)'
collect2: ld returned 1 exit status
有一個明顯的問題,代碼沒有得到namespace
內提供來自或在:
g++ bar.o foo.o -o foobar
約在不確定的參考產生的編譯器錯誤bar
編譯單元。另外,當我試圖將DoSomething
的定義放在bar.h
頭文件中時,正如我想在單獨的.cpp文件中定義類模板方法時所想到的那樣,我會得到相同的錯誤。
你能否介紹一下我的編譯器鏈接錯誤?