c++ - 在独立文件中编写c++模板函数,并用g++ -c编译
问题描述
我写了两个c++代码文件:一个有main函数,命名为main.cpp:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b);
int main () {
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
另一个在其中定义了一个模板函数,名为 template-function.cpp:
template <typename T>
inline T const& Max (T const& a, T const& b) {
return a < b ? b:a;
}
然后我编译这两个文件:
g++ -c main.cpp
g++ -c template-function.cpp
g++ main.o template-fun.o -o main
它引发错误:
test-template.o: In function `main':
test-template.cpp:(.text+0x38): undefined reference to `int const& Max<int>(int const&, int const&)'
test-template.cpp:(.text+0x90): undefined reference to `double const& Max<double>(double const&, double const&)'
test-template.cpp:(.text+0x130): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const& Max<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status
如何解决这个问题,如果我想在它被调用的文件中定义模板函数。
解决方案
推荐阅读
- python - 如何根据另一列的值移动一列?
- python-3.x - InlineKeyboardButton 和 CallbackData
- excel - 对另一张表的数据进行排序
- python - python脚本上的文件描述符错误,但输出正确
- java - Android Fido2PendingIntent().launchPendingIntent 第一次失败,并连续工作
- javascript - SweetAlert2 获取上一步的值
- reactjs - 如何在 Reactjs 中使用 Zebradatepicker?
- java - 过滤可能为空的 SQL 行
- cassandra - cassandra where 子句,来自 udt 的一个字段
- swift - SwiftUI,如何翻译带有计时器样式的文本?