gpt4 book ai didi

先决条件更改后 Cmake 不重建依赖项

转载 作者:行者123 更新时间:2023-12-04 16:11:24 25 4
gpt4 key购买 nike

我有下面的依赖关系图

a.txt <- prereq <- stamp <- dest

其中prereqdest是目标,a.txtstamp是文件。我希望在 a.txt 更改时更新 stamp。

为此,我有以下 CMakeLists.txt 文件:

 cmake_minimum_required(VERSION 3.6)
project(sample)

# variable holding location of stamp and a.txt file
set(STAMP ${CMAKE_CURRENT_SOURCE_DIR}/stamp)
set(ATXT ${CMAKE_CURRENT_SOURCE_DIR}/a.txt)

add_custom_target(
prereq
DEPENDS ${ATXT}
)


add_custom_command(
OUTPUT ${STAMP}
COMMAND ${CMAKE_COMMAND} -E echo "Update stamp."
COMMAND ${CMAKE_COMMAND} -E touch ${STAMP}
DEPENDS prereq
)

add_custom_target(dest ALL DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/stamp)

最初,我有以下文件

$ ls
a.txt
CMakeLists.txt

在第一次运行 cmake 和 make 之后,我们得到了预期的行为,

$ cmake .
$ make
[ 0%] Built target prereq
[100%] Generating stamp
Update stamp.
[100%] Built target dest

但是,在触摸 a.txt 之后,我希望 stamp 得到更新,但它没有。

$ touch a.txt
$ make
[ 0%] Built target prereq
[100%] Built target dest

这是 cmake 中的错误还是预期的行为?我们如何在每次 prereq 更改时强制 cmake 运行 touch 命令?

最佳答案

add_custom_target()add_custom_command() 调用中的

DEPENDS 行为不同。

只需将 ATXT 移动为 add_custom_command(OUTPUT ${STAMP} ...) 调用的依赖项即可解决问题,因为在 中命名非输出文件>add_custom_target() 将不起作用。

参见 add_custom_command() documentation :

DEPENDS: Specify files on which the command depends. If any dependency is an OUTPUT of another custom command in the same directory (CMakeLists.txt file) CMake automatically brings the other custom command into the target in which this command is built. If DEPENDS is not specified the command will run whenever the OUTPUT is missing.

参见 add_custom_target() documentation :

DEPENDS: Reference files and outputs of custom commands created with add_custom_command() command calls in the same directory (CMakeLists.txt file).

add_custom_target() 中的DEPENDS 参数仅用于确定目标/自定义调用依赖性。

编辑:“后期依赖注入(inject)”的替代方案

  1. 如果您在同一个 CMakeLists.txt 文件中,您可以APPEND 依赖关系到之前的自定义命令 OUTPUT:

    add_custom_command(
    OUTPUT ${STAMP}
    COMMAND ${CMAKE_COMMAND} -E echo "Update stamp."
    COMMAND ${CMAKE_COMMAND} -E touch ${STAMP}
    )

    add_custom_target(dest ALL DEPENDS ${STAMP})

    add_custom_command(
    OUTPUT ${STAMP}
    DEPENDS ${ATXT}
    APPEND
    )
  2. 您可以添加一些虚拟输出来为您的 prereq 目标提供自定义命令,但是要重新触发 dest 的构建,您需要触摸一些输入或删除 dest 的输出(add_dependencies() 本身不会重新触发自定义目标,它只是确保先调用一个目标):

    add_custom_command(
    OUTPUT ATxtCheck
    COMMAND ${CMAKE_COMMAND} -E remove ${STAMP}
    COMMAND ${CMAKE_COMMAND} -E touch ATxtCheck
    DEPENDS ${ATXT}
    )

    add_custom_target(prereq DEPENDS ATxtCheck)

    add_custom_command(
    OUTPUT ${STAMP}
    COMMAND ${CMAKE_COMMAND} -E echo "Update stamp."
    COMMAND ${CMAKE_COMMAND} -E touch ${STAMP}
    DEPENDS prereq
    )

    add_custom_target(dest ALL DEPENDS ${STAMP})

引用资料

关于先决条件更改后 Cmake 不重建依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40032593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com