有效值有限的CMake变量 [英] CMake variable with limited valid values

查看:54
本文介绍了有效值有限的CMake变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于CMake的项目中,我的CMakeLists.txt中有一个变量,可用于定位后端.该变量的有效值受到限制,例如6.

In my CMake based project I have a variable in my CMakeLists.txt that enables what backend to target. The valid values for this variable are limited, say 6.

我想缓存有效值的列表,以便用户可以选择要启用的功能.CMake应该验证变量.

I want to cache a list of the valid values so that the user can select which feature to enable. CMake should validate the variable.

这可能吗?如果可以,怎么办?

Is this possible and if so, how?

推荐答案

如果要验证允许的值,则需要自己在 CMakeLists.txt 文件中进行操作.但是,您可以提供CMake值列表,以CMake GUI应用程序中STRING缓存变量的组合框形式显示(以及ccmake中基于ncurses的等效项).您可以通过设置缓存变量的STRINGS属性来实现.例如:

If you want to validate the allowable values, you'll need to do that yourself in your CMakeLists.txt file. You can, however, provide a list of values for CMake to present as a combo box for STRING cache variables in the CMake GUI app (and also an ncurses-based equivalent in ccmake). You do that by setting the STRINGS property of the cache variable. For example:

set(trafficLightColors Red Orange Green)
set(trafficLight Green CACHE STRING "Status of something")
set_property(CACHE trafficLight PROPERTY STRINGS ${trafficLightColors})

在该示例中,CMake GUI将显示 trafficLight 缓存变量,就像其他任何字符串变量一样,但是如果用户单击它以对其进行编辑,则将使用通用文本框,而不是得到一个组合框,其中包含项目 Red Orange Green .

In that example, the CMake GUI would show the trafficLight cache variable just like any other string variable, but if the user clicks on it to edit it, instead of a generic text box you'd get a combo box containing the items Red, Orange and Green.

虽然这不是100%可靠的验证,但确实可以帮助用户在使用GUI时仅输入有效值.但是,如果他们在命令行上使用cmake,则没有什么可以阻止他们将缓存变量设置为他们喜欢的任何值.因此,我建议使用STRINGS缓存变量属性来帮助您的用户,同时也要进行验证.如果您使用了上面示例的模式,那么您将已经有了有效值的列表,因此验证应该很容易.例如:

While this isn't 100% robust validation, it does help users enter only valid values if using the GUI. If they are using cmake at the command line though, there's nothing stopping them from setting a cache variable to any value they like. So I'd recommend using the STRINGS cache variable property to help your users, but also do validation. If you've used the pattern of the above example, you will already have list of valid values, so validation should be easy. For example:

list(FIND trafficLightColors ${trafficLight} index)
if(index EQUAL -1)
    message(FATAL_ERROR "trafficLight must be one of ${trafficLightColors}")
endif()

或者,如果您使用的是CMake 3.5或更高版本:

Or if you're using CMake 3.5 or later:

if(NOT trafficLight IN_LIST trafficLightColors)
    message(FATAL_ERROR "trafficLight must be one of ${trafficLightColors}")
endif()

这篇关于有效值有限的CMake变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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