-4

this is my code snnippet

// test.cpp
#include <iostream>
#include "test.h"
int main(){
  Test<int> test = Test<int>();

  test.add(1);
  test.print();
}

// test.h
#ifndef TEST
#define TEST
template <typename T> class Test{
public:
  T info;
  void print();
  void add(T i);
 };
#endif
// testT.cpp
#include <iostream>
#include "test.h"

template<typename T> void Test<T>::print()
{
   std::cout << info << std::endl;
}
template<typename T> void Test<T>::add(T i)
{
  info = i;
}

and i run this exec

g++ -c testT.cpp && g++ test.cpp -o a.out testT.o

i get this error

Undefined symbols for architecture x86_64:
  "Test<int>::add(int)", referenced from:
      _main in test-e89092.o
  "Test<int>::print()", referenced from:
      _main in test-e89092.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)  // in my macOS

i want to declare template class in head file and define method in other file,so i only compile the define method file not head file if i change the definition of method in template class. what should i do?

mch
  • 9,424
  • 2
  • 28
  • 42
向王涛
  • 1
  • 2

1 Answers1

0

A posible way to seperate template to cpp and header is to typedef it to the types you are using it from the source which define the functions bodies.

for example: in your code, if you'll add a typedef Test<int> __UNUSED_TEMP_INT__; in the bottom of testT.cpp it will compiled for int in a place it recognize the bodies. but than you can use the template only for int.

Other option is to include the source from the header, but then the cpp is just another header.

SHR
  • 7,940
  • 9
  • 38
  • 57