Check If C Function Exists using CMake

Check If C Function Exists using CMake

When building cross-platform software in C or C++, you often depend on system-provided functions or libraries whose availability can vary between operating systems, library versions, or toolchains. For example, certain standard or POSIX functions might exist on one platform but be missing or replaced on another. To make the project portable and avoid compilation errors, you need a reliable way to detect whether a particular C function is available before using it. This tutorial explains how to check if C function exists using CMake.

CMake provides built-in testing utilities. The check_function_exists command allows you to test the system for a function and conditionally enable or disable parts of the code based on the result.

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(CheckFunctionExists)

check_function_exists(explicit_bzero HAVE_EXPLICIT_BZERO)
if (HAVE_EXPLICIT_BZERO)
    # ...
endif ()

add_executable(${PROJECT_NAME} main.cpp)

When you run CMake, it will try to compile and link a small test program that calls the specified function. If the function exists in the system libraries, CMake defines the corresponding variable as TRUE. You can then use this variable in the CMake scripts or pass it to the source code via compile definitions to conditionally enable features that depend on that function.

By default, the check_function_exists command prints diagnostic messages like:

-- Looking for explicit_bzero
-- Looking for explicit_bzero - found

If you're performing multiple checks and want to keep the build logs clean, you can silence these messages by setting the variable CMAKE_REQUIRED_QUIET before calling the check function:

# ...

set(CMAKE_REQUIRED_QUIET TRUE)

include(CheckFunctionExists)

check_function_exists(explicit_bzero HAVE_EXPLICIT_BZERO)

# ...

Leave a Comment

Cancel reply

Your email address will not be published.