Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to put C++ function in header file

I've been looking at Boost and various other C++ libraries. The vast majority of Boost is implemented in header files.

My question is: under what conditions do you do a header-only implementation (like Boost) or also include a .cpp file?

like image 500
John Smith Avatar asked Mar 20 '10 21:03

John Smith


1 Answers

If you want to use a template in another translation unit (i.e. another source file), you should (almost always) define it in the header file. (There are exceptions, like the comments below point out, but IMHO this is a good rule of thumb.)

Same applies if you want to use an inline function from another translation unit.

Otherwise you should put the implementation into a separate .cpp file to minimize dependencies.

like image 144
Péter Török Avatar answered Sep 18 '22 23:09

Péter Török