Check Operating System using CMake

Check Operating System using CMake

When writing cross-platform CMake-based projects, you often need to tailor build configurations depending on the target operating system - for example, setting platform-specific compiler options, linking system libraries, or using OS-dependent source files. Fortunately, CMake provides built-in variables to detect the operating system at configuration time. This tutorial shows how to check operating system using CMake.

1. CMAKE_SYSTEM_NAME variable

The variable CMAKE_SYSTEM_NAME contains the name of the target operating system. Here's a simple CMakeLists.txt example how to use this variable:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
    message(STATUS "Linux")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Windows")
    message(STATUS "Windows")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Android")
    message(STATUS "Android")
elseif (CMAKE_SYSTEM_NAME STREQUAL "iOS")
    message(STATUS "iOS")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
    message(STATUS "macOS")
elseif (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
    message(STATUS "FreeBSD")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

You can find a full list of possible values for CMAKE_SYSTEM_NAME in the official documentation.

2. Built-in platform variables

CMake also provides a set of predefined boolean variables such as WIN32, LINUX, APPLE, and others. These variables make the CMake code easier to read and maintain. However, they are only available for the most commonly used operating systems.

# ...

if (LINUX)
    message(STATUS "Linux")
elseif (WIN32)
    message(STATUS "Windows (including Win64)")
elseif (ANDROID)
    message(STATUS "Android")
elseif (IOS)
    message(STATUS "iOS")
elseif (APPLE)
    message(STATUS "macOS, iOS, tvOS, visionOS or watchOS")
elseif (BSD)
    message(STATUS "DragonFlyBSD, FreeBSD, OpenBSD, or NetBSD")
endif ()

# ...

Leave a Comment

Cancel reply

Your email address will not be published.