C/C++ include header file order

c++ c
Anycorn picture Anycorn · May 4, 2010 · Viewed 117.3k times · Source

What order should include files be specified, i.e. what are the reasons for including one header before another?

For example, do the system files, STL, and Boost go before or after the local include files?

Answer

squelart picture squelart · May 4, 2010

I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.

My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:

  1. h file corresponding to this cpp file (if applicable)
  2. headers from the same component,
  3. headers from other components,
  4. system headers.

My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.