Namespaces
Variants

Source file inclusion

From cppreference.com
 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Includes header or other source file into current source file.

Syntax

#include < h-char-sequence > new-line (1)
#include " q-char-sequence " new-line (2)
#include pp-tokens new-line (3)
__has_include(< h-char-sequence >)
__has_include(" q-char-sequence ")
(4) (since C++17)
__has_include(< h-pp-tokens >)
__has_include(" s-char-sequence (optional) ")
(5) (since C++17)
1-3) The #include directive. Searches for a specific header or source file, and replaces the directive by the entire contents of the header or source file.
4,5) The __has_include expression. Checks whether a header or source file is available for inclusion.
If defined expressions appear in __has_embed expressions, the program is ill-formed.
new-line - The new-line character
h-char-sequence - A sequence of one or more h-char s, where the appearance of any of the following is conditionally-supported with implementation-defined semantics:
  • the character '
  • the character "
  • the character \
  • the character sequence //
  • the character sequence /*
h-char - Any member of the source character set(until C++23)translation character set(since C++23) except new-line and >
q-char-sequence - A sequence of one or more q-char s, where the appearance of any of the following is conditionally-supported with implementation-defined semantics:
  • the character '
  • the character \
  • the character sequence //
  • the character sequence /*
q-char - Any member of the source character set(until C++23)translation character set(since C++23) except new-line and "
pp-tokens - A sequence of one or more preprocessing tokens
h-pp-tokens - A sequence of one or more preprocessing tokens except >
s-char-sequence - A sequence of one or more s-char s (see string literal)

Explanation

1) Performs a header search . Searches a sequence of places for a header identified uniquely by h-char-sequence . How the places are determined or the header identified is implementation-defined.
If the search fails or identifies a header that cannot be processed by the implementation, the program is ill-formed.
2) Performs a source file search . Attempts to identify a source file that is named by q-char-sequence . The named source file is searched for in an implementation-defined manner.
If the implementation does not support a source file search for that q-char-sequence , or if the search fails, the result of the source file search is the result of a header search for that q-char-sequence .
If the search identifies a source file that cannot be processed by the implementation, the program is ill-formed.
3) If neither (1) nor (2) is matched, pp-tokens will undergo macro replacement. The directive after replacement will be tried to match with (1) or (2) again, where the treatment of whitespace is implementation-defined.
If the second attempt also fails, the behavior is undefined(until C++26)the program is ill-formed, no diagnostic required(since C++26). There will be no second round of macro replacement.
4,5) Searches for a header or source file identified by an invented #include directive, using all preprocessing tokens enclosed by the parentheses as the preprocessing tokens following #include, except that no further macro expansion is performed.
  • If these preprocessing tokens does not consist solely of a header name or cannot be combined into a single header name preprocessing token, the program is ill-formed.
  • The __has_include expression evaluates to 1 if the search for the header or source file succeeds, and to 0 if the search fails.

If the header identified by the header-name (i.e., < h-char-sequence > or " q-char-sequence ") denotes an importable header, it is implementation-defined whether the #include preprocessing directive is instead replaced by an import directive of the form

import header-name ; new-line

(since C++20)

__has_include can be expanded in the expression of #if and #elif. It is treated as a defined macro by #ifdef, #ifndef, #elifdef, #elifndef(since C++23) and defined but cannot be used anywhere else.

Notes

Typical implementations search only standard include directories for header search. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

The intent of source file search is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides.

When a file is included, it is processed by translation phases 1-4, which may include, recursively, expansion of the nested #include directives, up to an implementation-defined nesting limit. To avoid repeated inclusion of the same file and endless recursion when a file includes itself, perhaps transitively, header guards are commonly used: the entire header is wrapped in

#ifndef FOO_H_INCLUDED /* any name uniquely mapped to file name */
#define FOO_H_INCLUDED
// contents of the file are here
#endif

Many compilers also implement the non-standard pragma #pragma once with similar effects: it disables processing of a file if the same file (where file identity is determined in OS-specific way) has already been included.

A sequence of characters that resembles an escape sequence in q-char-sequence or h-char-sequence might result in an error, be interpreted as the character corresponding to the escape sequence, or have a completely different meaning, depending on the implementation.

A __has_include result of 1 only means that a header or source file with the specified name exists. It does not mean that the header or source file, when included, would not cause an error or would contain anything useful. For example, on a C++ implementation that supports both C++14 and C++17 modes (and provides __has_include in its C++14 mode as a conforming extension), __has_include(<optional>) may be 1 in C++14 mode, but actually #include <optional> may cause an error.

Example

#if __has_include(<optional>)
    #include <optional>
    #define has_optional 1
    template<class T>
    using optional_t = std::optional<T>;
#elif __has_include(<experimental/optional>)
    #include <experimental/optional>
    #define has_optional -1
    template<class T>
    using optional_t = std::experimental::optional<T>;
#else
    #define has_optional 0
    template<class V>
    class optional_t
    {
        V v{};
        bool has{};

    public:
        optional_t() = default;
        optional_t(V&& v) : v(v), has{true} {}
        V value_or(V&& alt) const&
        {
            return has ? v : alt;
        }
        // etc.
    };
#endif

#include <iostream>

int main()
{
    if (has_optional > 0)
        std::cout << "<optional> is present\n";
    else if (has_optional < 0)
        std::cout << "<experimental/optional> is present\n";
    else
        std::cout << "<optional> is not present\n";
    
    optional_t<int> op;
    std::cout << "op = " << op.value_or(-1) << '\n';
    op = 42;
    std::cout << "op = " << op.value_or(-1) << '\n';
}

Output:

<optional> is present
op = -1
op = 42

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 787 C++98 the behavior was undefined if an escape sequence is
resembled in q-char-sequence or h-char-sequence
it is conditionally-supported
CWG 3015 C++98 syntax (2) might fallback to syntax (1), but q-char-sequence is
incompatible with h-char-sequence (the former may contain >)
fallback is defined semantically
rather than syntactically
CWG 3016 C++17 the search performed by __has_include was always
well-formed because syntax (3) could always be matched
a header name needs to be
formed as the sole component
CWG 3018 C++17 defined expressions could appear in __has_include expressions prohibited

See also

A list of C++ Standard Library headers
C documentation for Source file inclusion