C++ why include related header first?

  • A+

Related to this question: C/C++ include file order/best practices

The best answer recommends to include the related header first.

Same for Google and Mozilla style guides.

However, in both cases, I couldn't find a good reason why you would do this.

Google and Mozilla coding rules look best to me, because they enforce you to include the most "standard" headers first.

This way, I think you are less likely to mess up the included files (for examples by undefining some macros used in the other headers etc.) so that looks like the best way to go for me.

But following that rationale, why would you include the related header first? Since any syntax error in it might mess all the following headers?

I would think including the related header last would be best instead.


It's to make sure your clients don't hate you when they include your library header.

If the header is brittle and subject to break on wrong inclusion order, it may appear to work in your environment when it isn't first - since you include the headers you need - but fail to compile for client code. Because it may not at all be obvious what other headers need to be pulled in for it to work.

Including first the header which corresponds to the current implementation file goes toward checking that the header is self-contained. Self-containment goes beyond just including the necessary headers. It also entails adding the required forward declarations for types you use in your API. Naturally your header will compile if you include the header for the type before it, but you may not wish to pull it in since you only depend on the type name in your API.

Some style guides prohibit forward declarations, so those may not be part of the rationale they pose.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: