【问题标题】:Can I define a structure data type in CMake?我可以在 CMake 中定义结构数据类型吗?
【发布时间】:2015-08-12 02:40:51
【问题描述】:

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 中,我们可以使用 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")

但它不像 C/C++ 中的struct targetProperty 那样清晰,我想知道是否还有其他聪明的选择。谢谢。

【问题讨论】:

    标签: cmake


    【解决方案1】:

    如果您需要将结构与 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_property 命令desctiption。或者问更具体的问题。

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2021-06-07
        • 2012-09-20
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        • 2021-10-15
        相关资源
        最近更新 更多