CMake Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it

We will demonstrate OS discovery with a very simple CMakeLists.txt:

  1. We first define the minimum CMake version and project name. Note that our language requirement is NONE:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(recipe-01 LANGUAGES NONE)
  1. Then we wish to print a custom message depending on the detected OS:
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(STATUS "Configuring on/for Linux")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
message(STATUS "Configuring on/for macOS")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows")
message(STATUS "Configuring on/for Windows")
elseif(CMAKE_SYSTEM_NAME STREQUAL "AIX")
message(STATUS "Configuring on/for IBM AIX")
else()
message(STATUS "Configuring on/for ${CMAKE_SYSTEM_NAME}")
endif()

Before testing it out, first examine the preceding code block and consider what behavior you expect on your system.

  1. Now we are ready to test it out and configure the project:
$ mkdir -p build
$ cd build
$ cmake ..
  1. Of the CMake output, one line is interesting here – on a Linux system, this is the line of interest (on other systems, the output will hopefully be different):
-- Configuring on/for Linux