Language-specific add_compile_options?

What’s the best way to set compiler flags for all objects compiled with a given language? Basically, I’d like to use add_compile_options to set flags for a specific language. Or I’d like a best-practices approach to this:

if (CMAKE_C_COMPILER_ID STREQUAL GNU)
    list(APPEND CMAKE_C_FLAGS -fopt-info-vec -fopt-info-loop)
    list(APPEND CMAKE_CXX_FLAGS -fopt-info-vec -fopt-info-loop)
elseif (CMAKE_C_COMPILER_ID STREQUAL Clang)
    list(APPEND CMAKE_C_FLAGS -Rpass=.*loop.*)
    list(APPEND CMAKE_CXX_FLAGS -Rpass=.*loop.*)
elseif( ... )
   ... other compilers ...
endif ()

My motivation is that I have a mixed C, C++, and CUDA project; and those opt report flags aren’t valide for nvcc.

Thanks!

You can use the $<COMPILE_LANGUAGE> genex to limit flags to be per-language. For the case here, you probably want $<COMPILE_LANG_AND_ID> instead. https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html

Awesome! Looks like this works for me (without enclosing it in if (CMAKE_C_COMPILER_ID STREQUAL GNU))

add_compile_options($<$<COMPILE_LANG_AND_ID:CXX,GNU>:-fopt-info-vec>)
add_compile_options($<$<COMPILE_LANG_AND_ID:C,GNU>:-fopt-info-vec>)

Actually, looks like I got something wrong with the generator expression. Does anything look off with my code above?

Problems were encountered while collecting compiler information:
	gcc: error: $<0:-fopt-info-vec: No such file or directory
	gcc: error: $<1:-fopt-info-vec: No such file or directory
	cc1: error: unrecognized command line option '-fopt-info-loop>'
	g++: error: $<1:-fopt-info-vec: No such file or directory
	g++: error: $<0:-fopt-info-vec: No such file or directory
	cc1plus: error: unrecognized command line option '-fopt-info-loop>'

Note that those error messages mention -fopt-info-loop, which is not present at all in the code you’ve shown. Can you show the real code?

Nevertheless, if it looks like this:

add_compile_options($<$<COMPILE_LANG_AND_ID:CXX,GNU>:-fopt-info-vec -fopt-info-loop>)

then it’s wrong, because a genex must be a single argument: for CMake, it’s just a string until generate time, and must survive as an intact string until then. So spaces in it require quoting (if you want them to appear as spaces), and lists (which you probably want in your case) must be composed using $<SEMICOLON>:

add_compile_options($<$<COMPILE_LANG_AND_ID:CXX,GNU>:-fopt-info-vec$<SEMICOLON>-fopt-info-loop>)

Hi, how to concatenate genex-es ?

I have already:

   add_compile_options(
      $<$<CONFIG:RELEASE>:-O3>
      $<$<CONFIG:RELEASE>:-Ob1>
   )

to which I now need to add the $<COMPILE_LANGUAGE:Fortran> genex, cause I am dealing with multiple languages project ?

I obviously tried

   add_compile_options(
      $<$<CONFIG:RELEASE>$<COMPILE_LANGUAGE:Fortran>:-O3>
      ...
   )

but did not work.

Thanks!

See the generator expression docs for details, but this should work:

$<$<AND:$<CONFIG:RELEASE>,$<COMPILE_LANGUAGE:Fortran>>:-O3>
1 Like