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

我可以在CMake中定义结构数据类型吗?,cmake,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; }; 在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;
};
在CMake中,我们可以使用列表模拟此结构:

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

但它不像C/C++中的
struct targetProperty
那样清晰,我想知道是否还有其他智能替代方案。谢谢

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

set(targetProperty_folder_name "the location for the folder")
set(targetProperty_lib_name "the name of the lib")
另一种方法是CMake用来模拟命令中的命名参数:

list(APPEND targetProperty FOLDER_NAME "the location for the folder")
list(APPEND targetProperty LIB_NAME "the name of the lib")
然后,您可以使用模块解析列表

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


有关复杂的框架解决方案,请参见。

如果需要将结构与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}")
CMake属性还可以与源目录相关联,这允许某种继承

有关更多信息,请参见
define_属性
命令。或者问更具体的问题