Namespaces, Includes, and the Standard Library

Header Include Order

Does the order of #include directives matter? If so, what's the correct order?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Namespaces, Includes, and the Standard Library

A quick introduction to namespaces in C++, alongside the standard library and how we can access it

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Namespaces, Includes, and the Standard Library

A quick introduction to namespaces in C++, alongside the standard library and how we can access it

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved