10

I would like to use a cmake option inside a generator expression in order to turn on a certain compile flag. From the documentation it is not clear to me how to achieve this.

I would like to write something like

option(MYOPTION " ... " OFF)
...
add_compile_options($<$<MYOPTION>:-lblas>)

which does not work.

Is there a way to achieve this?

Wentzell
  • 183
  • 1
  • 8

1 Answers1

15

Your example doesn't really specify a use case for this, and I think there are other ways of going about it (as well as -lblas being a linker flag not a compile option.) Just off of the information you provide, it looks like what you might want is:

option(MYOPTION "My Option" OFF)
...
add_compile_options($<$<BOOL:${MYOPTION}>:-lblas>)
#(or maybe you want?)
target_compile_definitions(YOUR_TARGET PRIVATE $<$<BOOL:${MYOPTION}>:-lblas>)

$<$<BOOL:...>:...> needs a variable to assist with evaluating (which MYOPTION fulfills. There are other logical expressions listed in the documentation that you may use.

c4pQ
  • 884
  • 8
  • 28
Cinder Biscuits
  • 4,880
  • 31
  • 51
  • 3
    CMake documentation for [add_compiler_options](https://cmake.org/cmake/help/v3.9/command/add_compile_options.html) command explicitely says, that it can use generator expressions. In general, generator expressions are allowed whenever CMake docs say so. – Tsyvarev Oct 17 '17 at 20:55
  • Thank you for pointing that out, @Tsyvarev. I will correct my answer. – Cinder Biscuits Oct 17 '17 at 20:57
  • 1
    @Cinder Biscuits Thank you for your answer. The -lblas example was indeed badly chosen. My usecase is for making option specific defines in the end. $:...> works perfectly! – Wentzell Oct 18 '17 at 08:16
  • FYI, there is an open bracket missing in the answer's examples. – HunterZ Feb 11 '20 at 22:30