cmake add_custom_command that is executed on every

2019-07-24 13:50发布

I want to have something in CMake that will be executed whenever I enter make

add_custom_command(
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/build_date.cc
    PRE_BUILD
    COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/mk_build_date.py 
            ${CMAKE_CURRENT_BINARY_DIR}/build_date.cc
)
add_custom_target(build-date-xxx 
                  ALL
                  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/build_date.cc)

thats what I'm currently doing. unfortunately make build-date-xxx will generate the file only once.

even without the add_custom_target declaration the file is only build once.

the result should be something like this in GNU Make

.PHONY all: 
    echo "hallo welt"
all: foo.c bar.c
%.c:
    touch $@

in that makefile whenever make is entered. since all is the first target it will always be invoked and the custom command echo "hallo welt" is actually executed.

2条回答
Luminary・发光体
2楼-- · 2019-07-24 14:26

Try using ADD_CUSTOM_TARGET and use the argument ALL in it. Then make your main target dependent on this custom target.

查看更多
\"骚年 ilove
3楼-- · 2019-07-24 14:27

Reverse your order... have a custom target with no dependencies (no DEPENDS) that generates your file, and add a custom command that depends on this target, mentions that it OUTPUTs the file, and doesn't actually do anything (e.g. COMMAND ${CMAKE_COMMAND} -E echo). Then mention the output file somewhere (presumably you have it as a source of a library or executable). (You can also use ALL for the custom target, but I'm assuming that some code object actually uses the output file, so you'd want said code object to depend on the output file.)

Ideally you'd want to refrain from modifying the file unless something actually changes, or else you won't ever get a no-op build. (How to do this is left as an exercise for the reader.)

查看更多
登录 后发表回答