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:
<cstdio>
.<iostream>
or <vector>
.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.
Answers to questions are automatically generated and may not have been reviewed.
A quick introduction to namespaces in C++, alongside the standard library and how we can access it