Include directives order in source file and in header file

164 Views Asked by At

Which is the recommended order in which the #include directives are supposed to be listed? I could not find any answer in the C++ Core Guidelines

For example, should they be ordered like this:

#include "OtherHeaderInCurrentLib.h"
#include <third_party_library/header.h>
#include <iostream>

Or should they be ordered like this:

#include <iostream>
#include <third_party_library/header.h>
#include "OtherHeaderInCurrentLib.h"

And is there any difference between the recommended ordering when they are listed inside a source files and when they are listed inside a header files?

1

There are 1 best solutions below

5
On

A disadvantage of including standard, or third party headers before first party custom headers is that it will be very easy to accidentally depend on headers which you forgot to include directly. This will cause problems when the indirect inclusion is removed due to unrelated changes, or the custom header is included into context that doesn't have that missing dependency.

In the typical x.hpp, x.cpp "module" structure (not to be confused with C++20 modules), including x.hpp as the first header in x.cpp ensures that all such headers will have at least one translation unit where they are included first, avoiding the problem of undetected missing inclusions within x.hpp.

Other than that, it is a good idea to keep the inclusions in order so that it is easy to see what the dependencies are at a glance. Grouping by library, and sorting groups alphabetically are typical ways to keep the inclusions in order.