Header Include Order
Does the order of #include
directives matter? If so, what's the correct order?
The order of #include
directives can matter in some cases, due to macro definitions, type definitions, or inline functions in headers.
The general rule is to include headers in the following order:
- Related header: If a source file implements functions declared in a header file, include that header file first.
- C system headers: Headers from the C standard library, such as
<cstdio>
. - C++ standard library headers: Such as
<iostream>
or<vector>
. - Other libraries' headers: Headers from third-party libraries.
- Your project's headers: Headers specific to your project.
Within each category, headers should be ordered alphabetically.
Here's an example:
// my_class.cpp
#include "my_class.h" // Related header
#include <cstdio> // C system header
#include <algorithm> // C++ standard library
#include <iostream> // C++ standard library
#include <vector> // C++ standard library
#include <some_lib.h> // Other library
#include "my_project.h" // Your project's header
#include "utils.h" // Your project's header
This order ensures that the related header is included before anything else, system headers come before user headers, and within each category, headers are ordered alphabetically for easy scanning.
However, in most cases, the order of #include
directives doesn't matter as long as the required declarations are available when needed. Modern compilers are pretty good at handling include order.
Namespaces, Includes, and the Standard Library
A quick introduction to namespaces in C++, alongside the standard library and how we can access it