Examples: Why is implementation code in header files?

FWIW thinking about how our SOUL codebase has ended up being structured (which is a good example at about 15 KLoC of extremely gnarly logic), a rough overview is:

  • the nature of writing a compiler means you have a lot of classes, mostly small. And almost all the small classes (certainly anything under about 200LoC) are inline
  • many bigger classes that are only used by a single piece of client code (i.e. are only included in a single .cpp file) are inline
  • classes that are widely used across the whole codebase and whose implementation is non-trivial get split into h/cpp
  • Some classes work best as an inline class and a public function that acts as the way you interact with it, rather than making the class itself public.

So probably about 80% inline is my guess (maybe more, actually)

As a beginner, my advice is: just write everything inline and worry about more important things. It’s easier to see what you’re doing if everything’s in one place, and by the time you have a reason to want header/cpp (i.e. you’ve written a lot of code) then you’ll probably have more of an understanding of how it all works.

I always find it painful to see code where beginners have laboriously split the most trivial classes out into pairs of files with just a few lines each, just because they heard somewhere that that’s what you’re “supposed” to do!

10 Likes