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

How to do it

Now let us turn to the CMake side. In the CMakeLists.txt file, we need to apply the following:

  1. We first define the executable and its source file dependency:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(recipe-04 LANGUAGES CXX)

add_executable(arch-dependent arch-dependent.cpp)
  1. We check for the size of the void pointer type. This is defined in the CMAKE_SIZEOF_VOID_P CMake variable and will tell us whether the CPU is 32 or 64 bits. We let the user know about the detected size with a status message and set a preprocessor definition:
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
target_compile_definitions(arch-dependent PUBLIC "IS_64_BIT_ARCH")
message(STATUS "Target is 64 bits")
else()
target_compile_definitions(arch-dependent PUBLIC "IS_32_BIT_ARCH")
message(STATUS "Target is 32 bits")
endif()
  1. Then we let the preprocessor know about the host processor architecture by defining the following target compile definitions, at the same time printing status messages during configuration:
if(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i386")
message(STATUS "i386 architecture detected")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "i686")
message(STATUS "i686 architecture detected")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "x86_64")
message(STATUS "x86_64 architecture detected")
else()
message(STATUS "host processor architecture is unknown")
endif()

target_compile_definitions(arch-dependent
PUBLIC "ARCHITECTURE=${CMAKE_HOST_SYSTEM_PROCESSOR}"
)
  1. We configure the project and note the status message (the precise message may of course change):
$ mkdir -p build
$ cd build
$ cmake ..

...
-- Target is 64 bits
-- x86_64 architecture detected
...
  1. Finally, we build and execute the code (the actual output will depend on the host processor architecture):
$ cmake --build .
$ ./arch-dependent

x86_64 architecture. Compiled on a 64 bit host processor.