3

I have called a template in my C++ program:

const matrix::CMatrix<double> M1(3,3,{{5.0,0.0,2.0},{1.0,1.0,3.0},{6.0,7.0,7.0}});

i got such linker error:

tests.h:15: undefined reference to `matrix::CMatrix<double>::CMatrix(int, int, std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >)'

after massive search, finally i realized it is because i have separated my h and cpp files and template does not tolerate it. In C it is suggested to separate c and h files and using Makefile. But according to such problems in c++ is it still suggested to separate cpp and h files? It is not clean way to implement some templates in h files and some other functions in cpp file. what should i do?

edit:

matrix.h

template<typename T>
class CMatrix
{
.....

matrix.cpp

implementation of CMatrix

main.cpp

defining M1
sizben
  • 33
  • 4
  • What do you mean by "separated"? Where is your template declared (in .cpp or in .h) and where it is used? – Ashalynd Dec 13 '14 at 08:03

3 Answers3

2

Yes you should separate CPP from .h files.
This is more than a suggestion.

The .cpp files are compiled into compilation units, which means every .cpp file gets compiled into an .obj file with all the code it has, and all the code it includes.

So if you have some code in a .h file that is included in many .cpp files, it gets compiled many times.

Now this fact can get ugly when you have multiple projects and libraries.

Anyway, templates are a different issue.
The template calsses don't really get compiled until they are instantiated (until you use them).
Then the compiler creates the needed code for the right type.
It does not just get compiled the first time the compliler sees the templated code (like "regular" code)

So, you need to have that templated code in a header file, so the compiler "sees" it in every compilation unit (.cpp) file that uses it.
So the compiler can create the right code where it is needed.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
1

If you want to use your templates across multiple files, put the template in a header file so you can include it elsewhere. If you just need the template within the file then put it in the cpp.

pje
  • 2,458
  • 1
  • 25
  • 26
0

If the templated methods are private, you can, and should, put the definitions (the method bodies) in the .cpp file. They only need to be be in the .hpp file if they are public.

There's a problem of putting everything in headers: If you draw a dependency tree of all your files, with main.cpp as root node, then it only works if there are no dependencies pointing upwards. That would of course be a great and simple design, but in practise you often want some backward references (could be anything, like a method taking a certain class as argument or having a certain class as member). At that point you could get lots of "incomplete class" compiler errors...