Identifying Fortran compiler with CMake

I see projects using a variety of less robust methods to detect which compiler is being used to thereby set compilation options. Although this discussion focuses on Fortran, it is easily and equally applicable to other languages such as C and C++.

Robust compiler detection

The most robust and canonical way to detect what specific compiler is being used in CMake is via the following variables that are set upon configuration:

  • CMAKE_Fortran_COMPILER_ID: tells the compiler vendor (GNU, Intel, Clang, etc.) Don’t use CMAKE_Fortran_COMPILER because there are several compiler executables per vendor and this will not be robust over time.
  • CMAKE_Fortran_COMPILER_VERSION: This allows for VERSION_LESS_EQUAL and the like in CMake ≥ 3.7 to allow newer / older options as compilers improve.

Example

cmake_minimum_required (VERSION 3.10)
project(myproj Fortran)

if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel)
  add_compile_options(-check all -fpe0 -warn -traceback -debug extended)
elseif(CMAKE_Fortran_COMPILER_ID STREQUAL GNU) # gfortran
  add_compile_options(-Wall -Werror=array-bounds -Wextra -Wpedantic)
elseif(CMAKE_Fortran_COMPILER_ID STREQUAL PGI)
  add_compile_options(-traceback)
elseif(CMAKE_Fortran_COMPILER_ID STREQUAL Flang) # cmake >= 3.10

endif()