添加以文件名作为目标的自定义命令

spo*_*ith 7 cmake

我想做一些事情add_custom_command,输出文件名作为生成的makefile中的目标.这样做有一种优雅的方式吗?

我见过的所有示例(例如CMake FAQ re:latex)用于add_custom_command说明如何生成所需的输出文件,然后add_custom_target创建目标.例如.:

add_executable (hello hello.c)
add_custom_command(OUTPUT hello.bin
                   COMMAND objcopy --output-format=binary hello hello.bin
                   DEPENDS hello
                   COMMENT "objcopying hello to hello.bin")
add_custom_target(bin ALL DEPENDS hello.bin)
Run Code Online (Sandbox Code Playgroud)

但是,生成的makefile中的目标名称bin不是hello.bin.有没有办法让hello.bin自己成为生成的makefile中的目标?

我试过的一些解决方案不起作用:

  • 更改为:会add_custom_target(hello.bin ALL DEPENDS hello.bin)导致makefile中出现循环依赖关系.

ric*_*chq 4

您可以通过生成 hello.bin 作为目标的副作用来实现这一点。您不是从 objcopy 生成 hello.bin,而是生成 hello.tmp。然后,作为副作用,您还将 hello.tmp 复制到 hello.bin。最后,您创建依赖于 hello.tmp 的虚假目标 hello.bin。在代码中:

add_executable (hello hello.c)
add_custom_command(OUTPUT hello.tmp
                   COMMAND objcopy --output-format=binary hello hello.tmp
                   COMMAND ${CMAKE_COMMAND} -E copy hello.tmp hello.bin
                   DEPENDS hello
                   COMMENT "objcopying hello to hello.bin")
add_custom_target(hello.bin ALL DEPENDS hello.tmp)
Run Code Online (Sandbox Code Playgroud)

问题是当你运行 clean 时 hello.bin 没有被清理。要使其正常工作,请添加:

set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES hello.bin)
Run Code Online (Sandbox Code Playgroud)