Should I separate cpp and h file in C++?

£可爱£侵袭症+ 提交于 2019-12-23 21:03:57

问题


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

回答1:


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.




回答2:


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.




回答3:


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...



来源:https://stackoverflow.com/questions/27456772/should-i-separate-cpp-and-h-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!