Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I not split my code into header and source files?

I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?

For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp file or a .h file?

like image 457
Dollarslice Avatar asked Oct 18 '11 10:10

Dollarslice


1 Answers

On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition.

In aesthetic terms, the answer could be something like "always", or "systematically". In any case, you should always have a header for every logical unit of code (e.g. one class or one collection of functions); and the source file is one that is possibly optional, depending on whether or not you have everything defined inline (exempting you from ODR), or if you have a template library.

As a meta strategy, you should seek to decouple the compilation units as much as possible, so that you can include only what's needed in a fine-grained way. This allows your project to grow without having compilation times become unbearable, and it makes it much easier to reuse code in other projects.

like image 104
Kerrek SB Avatar answered Oct 20 '22 00:10

Kerrek SB