CMake 多选项设置

CMake multiple-option setting

我正在开发一个使用 CMake 构建的项目,因此我正在为它编写 CMakeLists.txt。在这个文件中,我想要一个(缓存的)CMake 变量,它只能采用几个选项之一(我会以某种方式指定),而不是任何任意字符串。为简单起见,让我们把它当作一个字符串,可以接受 "red"、"green" 或 "blue" - 但不能接受其他任何东西。

除了设置任意字符串然后检查其有效性之外,我能否使用最新的 CMake 版本实现此目的?

答案可以在 Kitware 的一篇名为 "Constraining Values with ComboBoxes in CMake (cmake-gui)":

的博文中找到

So here’s how it works: for each cache entry that you want to constrain to some set of values, define it as usual with a default value as a STRING cache variable, for example:

set(BaseName "binary" CACHE STRING "BaseName chosen by the user at CMake configure time")

Now, after defining the cache entry with its initial default value, define the set of strings to which its value should be constrained:

set_property(CACHE BaseName PROPERTY STRINGS binary octal decimal hexadecimal)

After the set_property call, cmake-gui knows to present a drop-down combo box for editing the “BaseName” cache entry, and it knows that the four valid choices for this entry that it should present are binary, octal, decimal and hexadecimal.