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?
Ideally, all header files should be self-contained, and inclusion order should not matter. In practice, people often write header files that are not self-contained, and sometimes inclusion order does matter.
I think most (good) programmers tend to prefer tidy code, having some habits or rules to stick to. One such rule/habit is the order of #include directives. While having a rule of thumb to stick to is good, some are better than other.
In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.
A header file is a file containing C declarations and macro definitions (see Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive ' #include '.
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.:
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #include
d without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With