C++ / C __has_include macro

GCC 5 enabled the __has_include macro that checks if a source file exists. __has_include() was made language standard syntax in C++17 and C23. __has_include("file.h") checks if “file.h” exists as a file on the compiler includes paths, but not if “file.h” can be included with the specified compiler language standard.

Watch out for buggy __has_include() in GCC < 10. We found that __has_include("linux/magic.h") with quotes "" instead of the usual carets __has_include(<linux/magic.h>) was needed specifically for header linux/magic.h. Other systems libraries with carets worked as expected even with GCC < 10.

#if __has_include("linux/magic.h")  // quotes needed for GCC < 10
#  include <linux/magic.h>
#endif

Examples

Compile and run the example number.cpp code.

% c++ -std=c++20 numbers.cpp

% ./a.out

3.14159

numbers.cpp:

#if __has_include(<numbers>)
#  define HAVE_NUMBERS
#  include <numbers>
#endif

#include <iostream>
#include <cstdlib>

int main(){
    // numbers example:
#ifdef HAVE_NUMBERS
    std::cout << std::numbers::pi << std::endl;
#else
    std::cout << "std::numbers::pi not available" << std::endl;
#endif
    return EXIT_SUCCESS;
}