Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate boolean variable in CMake?

Tags:

cmake

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.

like image 200
thiagowfx Avatar asked Jan 20 '17 22:01

thiagowfx


1 Answers

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}")
like image 171
usr1234567 Avatar answered Sep 16 '22 11:09

usr1234567