C Header Files – Best Practices for C Header File Order

Architectureccoding-style

I see that in many projects and examples that local includes are listed before external libs and before header files for built in compiler functionality.

Is there any advantage here that I am missing?

I have always used the following model:

1) built in header files
2) External lib header file
   A) External lib dependent on previous lib header file
3) custom project libs
4) local project header files

For example:

#include <stdio.h>
#include <stdlib.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "DisplayInfo.h"

#include "projectModule.h"

Is this wrong or bad practice?

Best Answer

Is there any advantage here that I am missing?

Yes, there is. I, along with a large number of software projects, used to follow the practice outlined in the question. Many projects, including modern ones I work on, now take the opposite approach in a source file:

  1. The header file that declares the functions being defined in the source file is the very first that is included.
  2. Other header files from the same project are included next.
  3. Header files from non-standard projects (e.g., eigen, boost, Qt) are included after local headers.
  4. Finally, standard header files are included last.
  5. Out of order inclusions need to be clearly documented with regard to why the header was not included in the above order.


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. To combat the first problem, that the first included file is the header file that declares the functions that are being defined in a source file creates a nice test that a header file is indeed self-contained. Compilation errors that result from that very first included file means there's a bug in that header.

To combat the second problem (an out of order inclusion is necessary), that should be viewed as a code smell. If the code smell is in your own project code, the best thing to do is do fix it. Code smells are occasionally a stinky necessary. Suppose, for example, you are using what would otherwise be a great third party library were it not for the fact that its header files are not self-contained. You use the library because all alternatives are worse, but you document the out of order inclusions.

This latter problem is becoming rarer as projects adopt inside-out inclusion practices (local first, system last). That old-style inclusion order hurts software quality.

Related Topic