Search code examples
c++header-files

Why include the corresponding header first?


On the question C/C++ include header file order, the best answer recommends to include the corresponding 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 corresponding header first? Since any syntax error in it might mess all the following headers?

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


Solution

  • 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.