0

I wrote two c++ code files: The one has main function, named 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;
}

The another one have a template function defined in it, named template-function.cpp:

template <typename T>
inline T const& Max (T const& a, T const& b) { 
   return a < b ? b:a; 
}

Then I compile these two file with:

g++ -c main.cpp
g++ -c template-function.cpp
g++ main.o template-fun.o -o main

It raise error:

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

How to solve this, if I want to define template function not in the file which it be called.

zhonhel
  • 11
  • 2

0 Answers0