How to do it

Let us build a corresponding CMakeLists.txt instance, which will enable us to conditionally compile the source code based on the target OS:

  1. We first set the minimum CMake version, project name, and supported language:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(recipe-02 LANGUAGES CXX)
  1. Then we define the executable and its corresponding source file:
add_executable(hello-world hello-world.cpp)
  1. Then we let the preprocessor know the system name by defining the following target compile definitions:
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_compile_definitions(hello-world PUBLIC "IS_LINUX")
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
target_compile_definitions(hello-world PUBLIC "IS_MACOS")
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
target_compile_definitions(hello-world PUBLIC "IS_WINDOWS")
endif()

Before continuing, first examine the preceding expressions and consider what behavior you expect on your system.

  1. Now we are ready to test it out and to configure the project:

$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./hello-world

Hello from Linux!

On a Windows system, you will see Hello from Windows!; other operating systems will yield different outputs.