Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

cmake - Adding a custom command with the file name as a target

I'd like to do something like add_custom_command, with the output file name as a target in the generated makefile. Is there an elegant way of doing this?

All the examples I've seen (such as the CMake FAQ re: latex) use add_custom_command to tell how to generate the desired output file, and then add_custom_target to create a target. For example.:

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)

However, the target name in the generated makefile is then bin rather than hello.bin. Is there a way to make hello.bin itself a target in the generated makefile?

Some solutions I've tried that don't work:

  • Changing to: add_custom_target(hello.bin ALL DEPENDS hello.bin) results in a circular dependency in the makefile.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do it by generating your hello.bin as a side effect of a target. Instead of generating hello.bin from objcopy, you generate hello.tmp. Then as a side effect you also copy hello.tmp to hello.bin. Finally, you create the phony target hello.bin that depends on your hello.tmp. In code:

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)

The problem with that is that hello.bin is not cleaned when you run clean. To get that working, add:

set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES hello.bin)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...