0

My template class compile successful but link error.

Error message:
Undefined symbols for architecture x86_64: 
"calculate<int>::plus(int, int)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Code is very simple:
1. calcualte.hpp

template <class T>
class calculate {
  public:
    T plus(T a, T b);
};

2. calculate.cpp

template <class T>
T calculate<T>::plus(T a, T b) {
   return a+b;
}

3. main.cpp

calculate<int> cal;

int a = cal.plus(11,20);

If I move the code in calculate.cpp to calculate.hpp, it will build successful. It should be link configuration in XCode. Anyone can help?

  • Btw. this is not an XCode specific issue - it's a general C++ issue. – Scheff's Cat May 08 '20 at 15:30
  • I found if i #include "calculate.cpp" than it works. Does anyone know why. – 林軒宇 May 10 '20 at 10:05
  • Of course. In C++, it is usual that `.cpp` (or `.cc`) file represent translation units - i.e. files which are compiled on its own. `.h` (or `.hpp`) files, in opposition, represent header files dedicated for `#include`s. Following the convention, `.cpp` files shouldn't be `#include`d as this may result in duplicated symbols if they contain definitions. In your case, the `.cpp` file contains part of the template definition. Including them breaks the usual conventions but fixes the lack of known template implementation in your case. – Scheff's Cat May 10 '20 at 13:17
  • Concerning "convention", the C++ compiler takes files given as arguments as translation units while headers are not given as arguments. The suffix has minor meaning although there might be exceptions. (I believe `gcc` may "switch" to C++ if the file suffix indicates this. Other compilers might do similar. FYI: [SO: Compiling a C++ program with gcc](https://stackoverflow.com/q/3178342/7478597)) – Scheff's Cat May 10 '20 at 13:21

0 Answers0