5

I'm using CMake for a moderate-sized Fortran project; sometimes I build it with gfortran, other times with ifort. When I want to do a debug build, the compiler flags are different; I'd like to have CMake automatically check which compiler is being used and set the flags accordingly.

It looks like this answer shows how to do the same thing for different C++ compilers. There's an example of how to check compilers with Fortran, using

if (Fortran_COMPILER_NAME MATCHES "gfortran.*")

However, this fails to invoke the conditional, because CMake has decided to use f95. Of course, f95 happens to alias to gfortran, but CMake doesn't detect that.

What's the right way to do this?

Community
  • 1
  • 1
Daniel Shapero
  • 1,869
  • 17
  • 30

3 Answers3

9

You can use also use CMAKE_Fortran_COMPILER_ID:

if ("${CMAKE_Fortran_COMPILER_ID}" MATCHES "Intel")
  # something
elseif("${CMAKE_Fortran_COMPILER_ID}" MATCHES "GNU")
  # something else
endif

Best way is to read file CMakeDetermineFortranCompiler.cmake and related files referenced from it.

Peter Petrik
  • 9,701
  • 5
  • 41
  • 65
3

Rather than trying to special case for different compilers you should actually test that your compiler supports the flags you want to set using check_fortran_compiler_flag like so:

include(CheckFortranCompilerFlag)
check_fortran_compiler_flag("-my-flag" _my_flag)
if(_my_flag)
  set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -my-flag")
endif()

This is both safer and (I think) simpler because you don't need the implied knowledge of which compiler (and version) supports which flag.

kynan
  • 13,235
  • 6
  • 79
  • 81
0

It's simple. Only indicate the full path of compiler installed e.g.gfortran. the code: cmake -DCMAKE_fortran_PATH=/usr/bin/gfortran