C++ – Should Own Header Files Be Included First or Last

cheadersinclude

I was revisiting my question How can I prevent header hell?, when I noticed a comment which said

A good technique for ensuring a header is independent is having a rule that the source file always includes its own header first. This will catch cases where you need to move dependency includes out of the implementation file into the header file

I am not sure that I follow that, and the reverse seems to have been the rule everywhere that I have worked. I never thought about it, or questioned it.

Are there any technical reasons for a .C or .CPP file to #include its own header file either for or last, or does it make no difference?

I am looking for technical reasons, not opinions. Nothing with “best”, which would be opinion. Answers which might help to prevent problems when refactoring or adding/removing other #includes are welcome.

Best Answer

#include directives are processed in the order in which they are encountered in the sources. Conceptually, when a #include is encountered, that directive is replaced with the content of the referenced file and after that processing continues with the modified source (so, processing continues on the first line that came from the included file).

If the very first #include directive in a source file is for the header that corresponds to that source file, then you can be sure that no other headers have been processed yet and you can prove that your header does not depend on some other header being included before it.

Other than that, it does not make any difference at all to the C or C++ compiler in which order header files are listed, as long as the constraint is met that every identifier is declared before it is used.