当依赖文件被修改时,如何让 CMake 重新运行 add_custom_command?

d4n*_*4nf 3 cmake

我希望每次修改我提供的列表中的文件时都重新运行自定义命令。

我的例子:我的项目有以下文件:

  • 主程序
  • CMakeLists.txt
  • dep1.txt
  • dep2.txt
cmake_minimum_required(VERSION 3.17)

project(dummy)
set(DummyFiles dep1.txt, dep2.txt)

add_executable(test_dummy main.cpp)

add_custom_command(TARGET test_dummy
COMMENT "ran custom command on file change"
DEPENDS ${DummyFiles}
)
Run Code Online (Sandbox Code Playgroud)

我的期望是,在我已经配置该项目,每次修改 dep1.txt 或 dep2.txt 并重新配置时,CMake 都会打印出COMMENT上面的部分。然而事实并非如此。

任何帮助,将不胜感激。

Tsy*_*rev 5

命令add_custom_command两个流程:“生成文件”和“构建事件”。

该选项DEPENDS仅适用于第一个流程 - “生成文件”,它需要OUTPUT作为第一个选项。

您用作TARGET命令的第一个选项,表示“构建事件”命令流。此命令流不支持DEPENDS选项(此命令流的概要中没有此类选项)。

我希望每次修改我提供的列表中的文件时都重新运行自定义命令。

为此,您需要使用with选项的第一个流程add_custom_commandOUTPUT

您可以使用虚拟文件作为输出,因此构建系统可以将该文件的时间戳与部分文件的时间戳进行比较DEPENDSOUTPUT每当发现的时间戳早于其中之一的时间戳时DEPENDS,该命令将重新运行。

set(DummyFiles dep1.txt dep2.txt)

add_custom_command(OUTPUT dummy.txt
  COMMENT "ran custom command on file change"
  DEPENDS ${DummyFiles}
)

# Need to create a custom target for custom command to work
add_custom_target(my_target ALL
  # Use absolute path for the DEPENDS file.
  # Relative paths are interpreted relative to the source directory.
  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/dummy.txt
)
Run Code Online (Sandbox Code Playgroud)