CMake中的自动变量 [英] Automatic variables in CMake

查看:105
本文介绍了CMake中的自动变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多自定义的CMake命令,所以最终在构建脚本中重复了这种模式,例如

I have a lot of custom CMake commands, so I end up with a lot of repetition of this pattern in build scripts, e.g.

set(PREREQ ${CMAKE_CURRENT_SOURCE_DIR}/foo.txt ${CMAKE_CURRENT_SOURCE_DIR}/bar.txt)
add_custom_command(
    OUTPUT baz.txt
    COMMAND cat ${PREREQ} > baz.txt
    DEPENDS ${PREREQ}
)
add_custom_target(a ALL DEPENDS baz.txt)

在CMake中是否有等效的GNU Make自动变量( $ @ $< 等),这样我就可以避免两次指定输入/输出(依赖关系,输出和命令)?

Are there equivalents of GNU Make automatic variables in CMake ($@, $<, etc) so I can avoid specifying inputs/outputs twice (dependencies, output, and command)?

还有什么方法可以干它?

How else can I DRY it up?

推荐答案

如何使用自定义函数?对于您的示例脚本,它可能看起来像这样:

How about using custom functions? For your example script this could look like this:

function (add_custom_command_with_target _targetName _output)
    add_custom_command(
        OUTPUT ${_output}
        COMMAND cat ${ARGN} > ${_output}
        DEPENDS ${ARGN}
    )
    add_custom_target(${_targetName} ALL DEPENDS ${_output})
endfunction()

该函数可以通过以下方式调用:

The function can be invoked in the following way:

add_custom_command_with_target(a baz.txt ${CMAKE_CURRENT_SOURCE_DIR}/foo.txt ${CMAKE_CURRENT_SOURCE_DIR}/bar.txt)

在函数主体中,可以使用预定义变量 ARGN 保留最后一个预期参数之后的参数列表。这是您最接近GNU Make的预定义变量的地方。

In the function body you can use the predefined variable ARGN, which holds the list of arguments past the last expected argument. This is the closest thing you can get to GNU Make's predefined variables.

这篇关于CMake中的自动变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆