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.
Note that __has_include()
merely checks if the file exists, and not if it can be included with the specified compiler language standard.
For example, C++20 header <numbers>
would fail compilation (until we added the __has_include() logic inside the main function):
% g++-13 -std=c++17 numbers.cpp
numbers.cpp: In function 'int main()':
numbers.cpp:10:23: error: 'std::numbers' has not been declared
10 | std::cout << std::numbers::pi << std::endl;
but succeeds with:
% g++-13 -std=c++20 numbers.cpp
% ./a.out
3.14159
numbers.cpp:
#if __has_include(<numbers>)
# include <numbers>
#endif
#include <iostream>
#include <cstdlib>
int main(){
// numbers example:
#if __has_include(<numbers>)
std::cout << std::numbers::pi << std::endl;
#else
std::cout << "std::numbers::pi not available" << std::endl;
#endif
return EXIT_SUCCESS;
}