2

I have a problem connecting two .cpp files in C++. Here are my files

Header.h

//Header.h
template <class T> class asd{
asd();
check();
print();
}

file1.cpp

//file1.cpp
//defines all methods in class asd
#include "Header.h"
template<class T> asd<T>:: asd(T a, T b){//codes}
template<class T> T asd<T>:: check(T a){//codes}
template<class T> void asd<T>::print(){//codes}

file2.cpp

//file2.cpp
//main method
#include "Header.h"
int main(){//codes}

The thing I do not understand is that the code runs fine when I put main() inside file1.cpp, but it wont compile when I separate them into two files. Can someone please give pointers?

Edit: For those with the same problem, solution can be found here: http://www.cplusplus.com/forum/articles/14272/

txp111030
  • 305
  • 1
  • 4
  • 11

1 Answers1

3

Member functions of a class template should appear in the header file. Just move the function definitions from file1.cpp to Header.h.

Imagine you are the compiler. When compiling main, if you attempt to instantiate asd in any way, the compiler needs to be able to see the function definitions to generate the appropriate code. For example, if in main you do asd<int> my_asd;, the compiler needs to instantiate asd with T replaced with int. It can't do that for the functions if it can't see the function definitions.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • This would work if the problem wasnt specifically asking for us to make two separate .cpp files. Sorry I was not very clear with my question. Regardless, thanks for your response! – txp111030 Mar 24 '13 at 22:26
  • @user2205010 Some people like to have a `.h` file and a `.tpp` file, and you `#include` the `.tpp` file *at the bottom* of the `.h` file. This achieves the same thing. – Joseph Mansfield Mar 24 '13 at 22:27
  • Yes that could also be an answer. I have found my best solution and posted it on my original post. Turned out template explicit instantiation fixed my issues. Thank you very much! – txp111030 Mar 24 '13 at 22:29