0
私は3つのC++ファイルを持っています。sort.cpp
は、配列、配列の長さ、および比較に使用する関数を持つバブルソート関数を定義しています。 sort.h
には、名前空間内に関数プロトタイプが含まれています。実装をテストするためにmain.cpp
が使用されます。C++リンカエラー:関数テンプレートを使用しているときにシンボルが見つかりません
sort.h:
#ifndef SORT_H
#define SORT_H
namespace sort {
template <typename T>
void bubble(T*, int, bool (*)(T, T));
}
#endif
sort.cpp:
#include "sort.h"
template <typename T>
void sort::bubble(T *array, int length, bool (*compare)(T, T)) {
while (length != 0) {
int newLength {0};
for (int i {0}; i < length - 1; ++i) {
if (compare(array[i], array[i+1])) {
T temp {array[i]};
array[i] = array[i+1];
array[i+1] = temp;
newLength = i + 1;
}
}
length = newLength;
}
}
main.cppに:私はg++ main.cpp sort.cpp -std=c++11
でコンパイルすると
#include <iostream>
#include "sort.h"
bool larger(int x, int y) {
return x > y;
}
int main() {
int arr[] {3, 5, 1, 3, 7, 2};
sort::bubble(arr, 6, larger);
for(const auto e: arr)
std::cout << e << ' ';
std::cout << '\n';
return 0;
}
私はエラーに取得
Undefined symbols for architecture x86_64:
"void sort::bubble<int>(int*, int, bool (*)(int, int))", referenced from:
_main in main-767bbd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
sort.cppをコンパイルするときに使用するタイプがコンパイラによって認識されないため、エラーが発生しますか?だから、コンパイラはテンプレートの機能を生成しませんし、リンカはそれを使用するとそれを見つけることができませんmain.cpp
?
どうすればこの問題を解決できますか?