首页 > 解决方案 > 在独立文件中编写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

如何解决这个问题,如果我想在它被调用的文件中定义模板函数。

标签: c++gccg++

解决方案


推荐阅读