Check If C Header File Exists using CMake

Check If C Header File Exists using CMake

When developing cross-platform applications in C or C++, it's common to rely on system-specific headers that might not be available on all platforms. Some headers are present only on UNIX-like systems, while others are Windows-only or depend on specific library versions. To make the code portable and robust, it's a good idea to detect whether a header file exists before including it in the source. This tutorial shows how to check if a C header file exists using CMake.

CMake includes built-in tools for performing configuration checks. The check_include_file command lets you verify whether a specific header file is available on the system, allowing you to enable or disable portions of the code accordingly.

Here's a simple CMakeLists.txt example of how to use it

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

include(CheckIncludeFile)

check_include_file(unistd.h HAVE_UNISTD_H)
if (HAVE_UNISTD_H)
    # ...
endif ()

add_executable(${PROJECT_NAME} main.cpp)

When you run CMake, it generates and compiles a small test file that includes the specified header. If the compilation succeeds, the corresponding variable is set to TRUE. You can then use that variable in the CMake logic or pass it as a preprocessor definition to the source code to conditionally enable functionality.

By default, the check_include_file command outputs diagnostic messages such as:

-- Looking for unistd.h
-- Looking for unistd.h - found

If you're performing many such checks and want to keep the CMake output tidy, you can silence these messages by setting the variable CMAKE_REQUIRED_QUIET before running the check:

# ...

set(CMAKE_REQUIRED_QUIET TRUE)

include(CheckIncludeFile)

check_include_file(unistd.h HAVE_UNISTD_H)

# ...

Leave a Comment

Cancel reply

Your email address will not be published.