14

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?


Notes

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.

1
  • Do you mind accepting one of the answers?
    – usr1234567
    Feb 15, 2017 at 8:31

1 Answer 1

8

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}")
1
  • 3
    Another implementation of a similar negate function in this gist
    – Luca Cappa
    Jan 21, 2017 at 11:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.