avatar

Catalog
CMake Cookbook Notes 2: Detecting the Environment

Chapter 2 Detecting the Environment

2.1 Discovering the operating system

  • We can get info about the OS from variable CMAKE_SYSTEM_NAME :

    cmake
    1
    if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
  • We can always use forward slash (/) as path delimiter in CMake and it will automatically translate the slash for corresponding OS (e.g. for Windows, it’s backward slash)

2.2 Dealing with platform-dependent source code

  • CMake provides two (yep, still two) ways to add definitions to be passed to the preprocessor (which can be checked by #ifdef).

  • The first is on a per-target basis, using target_compile_definitions. While the second is on a global basis, using add_compile_definitons (also, add_definitions can be used with an extra -D):

    cmake
    1
    2
    3
    target_compile_definitions(hello PUBLIC "IS_LINUX")
    add_compile_definitions("IS_LINUX")
    add_definitions(-DIS_LINUX)

2.3 Dealing with compiler-dependent source code

  • We can get info about compiler from variable CMAKE_CXX_COMPILER_ID:

    cmake
    1
    target_compile_definitions(hello-world PUBLIC "COMPILER_NAME=\"${CMAKE_CXX_COMPILER_ID}\"")
    c++
    1
    std::cout << "compiler name is " COMPILER_NAME << std::endl;

2.4 Discovering the host processor architecture

  • We can get info about the processor (like architecture, 32 bit or 64 bit) from variables CMAKE_HOST_SYSTEM_PROCESSOR and CMAKE_SIZEOF_VOID_P.

  • When add_executable, it’s not necessary to specify the source files immediately, we can defer it with target_sources:

    cmake
    1
    2
    3
    4
    5
    6
    7
    8
    9
    add_executable(arch-dependent "")

    if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i386")
    target_sources(arch-dependent PRIVATE arch-dependent-i386.cpp)
    elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "x86_64")
    target_sources(arch-dependent PRIVATE arch-dependent-x86_64.cpp)
    else()
    message(STATUS "host processor architecture is unknown")
    endif()

2.5 Discovering the host processor instruction set

  • We can get info about the system on which CMake runs, using cmake_host_system_information.
  • And we can use configure_file to configure a .h from a .h.in.

2.6 Enabling vectorization for the Eigen library

  • check_cxx_compiler_flag from module CheckCXXCompilerFlag can be used to check whether a compiler flag is available with the current compiler and store the result of check (true or false) to a variable.

    If the flag exists, we can then add it with target_compile_options introduced before.

Author: Gusabary
Link: http://gusabary.cn/2020/10/15/CMake-CookBook-Notes/CMake-Cookbook-Notes-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment