Fork me on GitHub

CMake lesson: Compilers and compiler flags

Overview

Teaching: 5 min
Exercises: 0 min
Questions
  • How can we select the compiler?
  • How can we change compiler flags?
Objectives
  • Learn how to display and change compilers and compiler flags.

How to specify the compiler

We can specify the compilers like this:

$ cd build
$ env FC=gfortran CC=gcc CXX=g++ cmake ..
$ make

Or by exporting the corresponding environment variables:

$ cd build
$ export FC=gfortran
$ export CC=gcc
$ export CXX=g++
$ cmake ..
$ make

Or by setting CMake variables:

$ cmake -D CMAKE_Fortran_COMPILER=gfortran -D CMAKE_C_COMPILER=gcc -D CMAKE_CXX_COMPILER=g++ ..

Controlling compiler flags

  • We can define compiler flags for different compilers and build types
if(CMAKE_Fortran_COMPILER_ID MATCHES Intel)
    set(CMAKE_Fortran_FLAGS         "${CMAKE_Fortran_FLAGS} -Wall"
    set(CMAKE_Fortran_FLAGS_DEBUG   "-g -traceback")
    set(CMAKE_Fortran_FLAGS_RELEASE "-O3 -ip -xHOST")
endif()

if(CMAKE_Fortran_COMPILER_ID MATCHES GNU)
    set(CMAKE_Fortran_FLAGS         "${CMAKE_Fortran_FLAGS} -Wall")
    set(CMAKE_Fortran_FLAGS_DEBUG   "-O0 -g3")
    set(CMAKE_Fortran_FLAGS_RELEASE "-Ofast -march=native")
endif()

...

Similarly you can set CMAKE_C_FLAGS and CMAKE_CXX_FLAGS.

This is how we set preprocessor definitions:

target_compile_options(sometarget PUBLIC -DVAR_SOMETHING -DENABLE_DEBUG -DTHIS_DIMENSION=137)

Controlling the build type

CMake distinguishes the following build types:

  • Debug
  • Release
  • RelWithDebInfo
  • MinSizeRel

We can select the build type on the command line:

$ cd build
$ cmake -D CMAKE_BUILD_TYPE=Debug ..
$ make

It is often useful to set:

# we default to Release build type
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Release")
endif()

The default compilation output is nice and compact. But sometimes we want to see the current compiler flags and the gory compiler output:

$ make clean
$ make VERBOSE=1

The link line is saved in CMakeFiles/<target>.dir/link.txt.