- CMake Cookbook
- Radovan Bast Roberto Di Remigio
- 161字
- 2025-04-04 16:17:17
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:
- 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)
- Then we define the executable and its corresponding source file:
add_executable(hello-world hello-world.cpp)
- 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.
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.