Ternary operator in CMake's generator expressions

∥☆過路亽.° 提交于 2019-12-04 22:33:55

Note that cmake 3.8 added exactly what you want to generator expressions ...

$<IF:?,true-value...,false-value...>
true-value... if ? is 1, false-value... if ? is 0

Here's a working example, with a macro:

cmake_minimum_required(VERSION 2.8.12)

macro(ternary var boolean value1 value2)
    set(${var} $<${${boolean}}:${value1}>$<$<NOT:${${boolean}}>:${value2}>)
endmacro()

set(mybool 0)
ternary(myvar mybool hello world)

add_custom_target(print
    ${CMAKE_COMMAND} -E echo ${myvar}
    )

Create a CMakeLists.txt file and run cmake . && make print (generator expressions are only evaluated at build time).

Try changing the value of mybool to 0 or 1 and see what happens.

The following definition also works, and it is clearer:

cmake_minimum_required(VERSION 2.8.12)

macro(ternary var boolean value1 value2)
    if(${boolean})
        set(${var} ${value1})
    else()
        set(${var} ${value2})
    endif()
endmacro()

set(mybool 0)
ternary(myvar mybool hello world)

add_custom_target(print
    ${CMAKE_COMMAND} -E echo ${myvar}
    )

TL;DR

ternary(var boolean value1 value2)

means, comparing to C/C++:

int var = boolean ? value1 : value2;

Let's make it more explicit:

add_custom_command(TARGET myProject PRE_BUILD
    COMMAND cd \"D:/projects/$<IF:$<CONFIG:Debug>,Debug,Release>\"
    COMMAND call prebuild.bat)

Then in generated Visual Studio Project, in the property window of project "myProject".

When build configuration is "Debug", the evaluation process is:

  1. $<IF:$<CONFIG:Debug>,Debug,Release>
  2. $<IF:1,Debug,Release>
  3. Debug

When build configuration is "Release", the evaluation process is:

  1. $<IF:$<CONFIG:Debug>,Debug,Release>
  2. $<IF:0,Debug,Release>
  3. Release

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!