CMake variable with limited valid values

老子叫甜甜 提交于 2020-12-25 03:50:25

问题


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.

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?


回答1:


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})

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.

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()

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()


来源:https://stackoverflow.com/questions/39670879/cmake-variable-with-limited-valid-values

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