我可以在CMake中定义结构数据类型吗?

fee*_*ree 4 cmake

CMake中的主要数据类型是字符串,并且CMake中的几乎所有变量都基于字符串。我想知道是否可以创建类似于C / C ++结构的结构。我给出以下示例来说明我的问题:

使用C / C ++,我们可以通过以下方式定义结构:

struct targetProperty
{
   std::string folder_name;
   std::string lib_name;
   std::string exe_name;
   std::string lib_type;
};
Run Code Online (Sandbox Code Playgroud)

在CMake中,我们可以使用LIST来模拟此结构:

set(targetProperty "the location for the folder")
list(APPEND targetProperty "the name of the lib")
list(APPEND targetProperty "the name of the executable")
list(APPEND targetProperty "the type of the lib")
Run Code Online (Sandbox Code Playgroud)

但这还不如struct targetPropertyC / C ++ 清楚,我想知道是否还有其他明智的选择。谢谢。

Tsy*_*rev 5

如果您需要将结构与CMake目标(可执行文件,库,自定义目标)关联,最简单的方法是使用CMake属性:

define_property(TARGET PROPERTY folder_name
    BRIEF_DOCS "The location for the folder"
    FULL_DOCS "The location for the folder"
)
define_property(TARGET PROPERTY lib_name
    BRIEF_DOCS "The name of the lib"
    FULL_DOCS "The name of the lib"
)

... # Define other structure field as properties


# Add some CMake target
add_custom_target(my_target1 ...)

# Associate structure with target
set_target_properties(my_target1 PROPERTIES
    folder_name "dir1"
    ... # set other properties
)

# Use properties
get_target_property(my_target1_folder my_target1 folder_name)
message("folder_name for my_target1 is ${my_target1_folder}")
Run Code Online (Sandbox Code Playgroud)

CMake属性也可以与源目录关联,从而允许某种继承。

有关更多信息,请参见define_property命令说明。或问更具体的问题。


tam*_*nez 4

您可以使用变量名称后缀字段名称来模拟结构:

set(targetProperty_folder_name "the location for the folder")
set(targetProperty_lib_name "the name of the lib")
Run Code Online (Sandbox Code Playgroud)

另一种方法是 CMake 用于模拟命令中的命名参数的方法:

list(APPEND targetProperty FOLDER_NAME "the location for the folder")
list(APPEND targetProperty LIB_NAME "the name of the lib")
Run Code Online (Sandbox Code Playgroud)

然后您可以使用CMakeParseArguments解析列表

在这两种情况下,您都可以编写 setter 和 getter 宏来自动化操作。

有关复杂的框架解决方案,请参阅cmakepp/Objects