Rules of thumb for putting functions in header files

One of my most inviolable rules: only function bodies which are inline are allowed in header files. Anything else is asking for trouble with multiple definitions in the link phase.

Headers should be left predominantly for declarations rather than definitions. I have exceptions to that rule (being the flexible type) but none of them involve non-inlined function bodies.


My rule of thumb is "Not in the header, unless you have to." And as for convenience, do you find increased compilation times convenient?


There are a few obvious technical aspects - templates and inline functions must be in headers - headers included from multiple translation units must be wary of the One Definition Rule - more bluntly, you'd want a bloody good reason to even consider putting an out-of-line function implementation in a header, and I can't think of any times I've even been tempted.

So, the question boils down to:

    inline in header versus out-of-line in implementation file?

Factors:

  • you say you're designing application level code not libraries, so you don't (currently) have to worry about other teams getting dependent on your code, nor minimise their need to recompile (versus just relink) by keeping implementation out of line
    • BUT if you're writing good code that has any potential to become useful to other teams, then you might find yourself wishing you'd kept implementation private
  • inline versus out-of-line typically represents about an order-of-magnitude overhead for trivial data get/set functions... if you have functions that are called repeatedly from performance critical code, then you've reason to prefer inlining
  • in-header implementation (especially if intermingled with the declarations) can often obfuscate the API, but sometimes actually makes the code more self-documenting
  • localisation and removed redundancy (of combining declaration/definitions) definitely removes potential for typos/errors and can often improve productivity

Bottom line: if you're finding yourself doing it more and more, then it's obviously working for you and there's no particular reason to think you're about to get burnt. Keep an eye out for the potential issues but don't over-engineer the heck out of stuff based on some hypothetical and unlikely-to-materialise concern.