Open In App

__has_include in C++17

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The __has_include is a special operator to work with preprocessor directives that allow you to check if a particular header file is available for inclusion in your program. It is a conditional compilation feature introduced in C++17 that helps you write portable code that can handle different environments or platforms.

Syntax

#if __has_include(<header_file>)
// Code to be executed if <header_file> is available
#else
// Code to be executed if <header_file> is not available
#endif

where,

  • header_file: It is the header file that is to be included.

If the header file is available, the expression evaluates to 1, otherwise, it evaluates to 0.

Example

Here’s an example to show how you can use __has_include:

#if __has_include(<iostream>)
// The <iostream> header is available
#include <iostream>
#else
// The <iostream> header is not available
// Handle the absence of <iostream> here
#endif

In the above example, the code checks if the <iostream> header file is available. If it is, the code includes <iostream> and proceeds with using its functionality. Otherwise, it can take an alternative path to handle the absence of <iostream>.

Implementation

The below C++ code checks for the availability of the <vector> header file using the __has_include macro.

C++




// C++ code that demonstrates the
// usage of __has_include macro
  
#include <iostream>
  
// checking if <vector> is available
#if __has_include(<vector>)
#include <vector>
#else
#error The file is not available
#endif
  
using namespace std;
int main()
{
    cout << "The <vector> file is available";
    return 0;
}


Output

The <vector> file is available

Explanation

In this example, the code checks if the <vector> header file is available using __has_include. If it is available, it proceeds with using its functionality. It also prints a message to indicate whether the header is available or not. If <vector> is not available, you can provide an alternative code or error handling in the else block.


Like Article
Suggest improvement
Share your thoughts in the comments