Suppose I set the following variable in CMake:
set(foo TRUE)
Now, I want to define a bar
variable with the opposite boolean value of foo
(in other words: in this context, I want bar
to be FALSE
, or equivalent, like false
or 0
). One way of completing this is:
if(foo)
set(bar FALSE)
else()
set(bar TRUE)
endif()
However, this is kinda verbose. How can I accomplish the same thing in fewer lines?
I tried to use generator expressions, but they don't seem to work in the set
command:
set(bar $<NOT:${foo}>)
Or even
set(bar $<NOT:foo>)
Won't produce the desired result.
There is no way to evaluate an expression.
If you need it often, you can write a helper function to handle the inversion. The call signature is clumsy, because you have to pass the variable name and it's value.
cmake_minimum_required(VERSION 3.0)
project(InvertFunction)
function (invertBoolean varName varValue)
if(${varValue})
set(${varName} false PARENT_SCOPE)
else()
set(${varName} true PARENT_SCOPE)
endif()
endfunction()
set(foo true)
invertBoolean("foo" foo)
message("Invert foo: ${foo}")
set(bar false)
invertBoolean("bar" bar)
message("Invert bar: ${bar}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With