CMake生成器表达式中的三元运算符 [英] Ternary operator in CMake's generator expressions

查看:374
本文介绍了CMake生成器表达式中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cmake的生成器表达式允许我使用逻辑表达式在某些函数调用中。例如,如果我想在调试模式下添加 / MTd 编译器标志,我可以说

Cmake's generator expressions allow me to use logical expressions within certain function calls. For instance, if I want to add the /MTd compiler flag in Debug mode, I can say

add_compile_options($<$<CONFIG:Debug>:/MTd>)

如果 CONFIG 等于调试,则会调用值为的 add_compile_options ,否则调用一个空字符串。

If CONFIG equals "Debug", this will call add_compile_options with the value "/MTd", otherwise with an empty string.

但是通常,我不想在一个值和一个空字符串之间做出决定,而是在两个值之间做出决定。在上面的示例中,如果 CONFIG not 调试,我想通过 / MT (无尾随d)。我很想拥有这样的语法:

But usually, I don't want to decide between a value and the empty string, but between two values. In the example above, if CONFIG is not "Debug", I want to pass /MT (without the trailing d). I'd love to have a syntax like this:

add_compile_options($<$<CONFIG:Debug>:/MTd:/MT>)

请注意,根据无效代码到CMake规格。我想出的最好的方法实际上是这样的:

Note that the above is not valid code according to the CMake specs. The best I have come up with that actually works is this:

add_compile_options($<$<CONFIG:Debug>:/MTd>$<$<NOT:$<CONFIG:Debug>>:/MT>)

这对我来说似乎是多余的。

This seems awfully redundant to me. Is there a shorter, more readable way to decide between two values?

注意:我意识到在这种特殊情况下,我可以这样写:

Note: I realize that in this special case, I could write this:

add_compile_options(/MT$<$<CONFIG:Debug>:d>)

但这对我来说似乎很棘手,仅在其中一个选项是另一个选项的子串的情况下有效。

But this seems rather hacky to me and only works in those cases where one option is a substring of the other.

推荐答案

请注意,cmake 3.8完全添加了您想要生成的表达式...

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

示例用法:

target_link_libraries(MyLib PUBLIC
    $<IF:$<CONFIG:Debug>,cppzmq,cppzmq-static>
    )

其中 cppzmq Debug build和 cppzmq-static 是用于其他情况的静态库,例如发布

Where cppzmq is shared library used in Debug build and cppzmq-static is static library used in other case e.g. Release

这篇关于CMake生成器表达式中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆