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

How to do it

We shall start out with the C++ example before moving on to the Fortran example:

  1. In the CMakeLists.txt file, we define the now familiar minimum version, project name, and supported language:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(recipe-03 LANGUAGES CXX)
  1. We then define the executable target and its corresponding source file:
add_executable(hello-world hello-world.cpp)
  1. Then we let the preprocessor know about the compiler name and vendor by defining the following target compile definitions:
target_compile_definitions(hello-world PUBLIC "COMPILER_NAME=\"${CMAKE_CXX_COMPILER_ID}\"")

if(CMAKE_CXX_COMPILER_ID MATCHES Intel)
target_compile_definitions(hello-world PUBLIC "IS_INTEL_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES GNU)
target_compile_definitions(hello-world PUBLIC "IS_GNU_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES PGI)
target_compile_definitions(hello-world PUBLIC "IS_PGI_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES XL)
target_compile_definitions(hello-world PUBLIC "IS_XL_CXX_COMPILER")
endif()

The previous recipes have trained our eyes and now we can already anticipate the result:

$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./hello-world

Hello GNU compiler!

If you use a different compiler vendor, then this example code will provide a different greeting.

The if statements in the CMakeLists.txt file in the preceding example and the previous recipe seem repetitive, and as programmers, we do not like to repeat ourselves. Can we express this more compactly? Indeed we can! For this, let us turn to the Fortran example.

In the CMakeLists.txt file of the Fortran example, we need to do the following:

  1. We need to adapt the language to Fortran:
project(recipe-03 LANGUAGES Fortran)
  1. Then we define the executable and its corresponding source file; in this case, with an uppercase .F90 suffix:
add_executable(hello-world hello-world.F90)
  1. Then we let the preprocessor know very compactly about the compiler vendor by defining the following target compile definition:
target_compile_definitions(hello-world
PUBLIC "IS_${CMAKE_Fortran_COMPILER_ID}_FORTRAN_COMPILER"
)

The remaining behavior of the Fortran example is the same as in the C++ example.