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 ...

Get CMake Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.