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:

  1. Related header: If a source file implements functions declared in a header file, include that header file first.
  2. C system headers: Headers from the C standard library, such as <cstdio>.
  3. C++ standard library headers: Such as <iostream> or <vector>.
  4. Other libraries' headers: Headers from third-party libraries.
  5. 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Use Namespaces in C++?
What are the benefits of using namespaces in C++? When should I use them in my code?
Multiple using Statements
Can I have multiple using statements for the same namespace in different scopes? What happens if I do?
Setting Include Paths
How do I set up my compiler to find header files in different directories?
Namespace Aliases
What is a namespace alias and when would I use one?
Explicit std:: Namespace
Why do you use explicit std:: namespace qualifiers in this lesson's code examples instead of 'using namespace std;'?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant