What is the name of CMake's default build targ

2019-08-10 06:10发布

问题:

I have a custom target, and I want it to depend on the default target (the one that is built with make).

add_custom_target(foo ....)
add_dependency(foo default_target_name_goes_here)

What is the name of the default target?

I've tried ALL, ALL_BUILD, MyProjectsName, DEFAULT,...

Finding anything in the CMake documentation is always an unsuccessful adventure...

UPDATE: it seems CMake was designed in such a way that this is extremely hard to fix/implement: bugreport getting +1's since 2009. Who indeed would like to have a custom target that depends on, for example, the all target? Or in other words: who does ever write make && make test?...

回答1:

The default build target does not exist as a CMake target at CMake configure time. It is only exists in the generated build system. Therefore it is not possible to have the default target depend on a custom target.



回答2:

I think a possible solution depends strongly on the use case. E.g. if this is for executing a test after the system has been build you would use CTest instead of calling make directly.

To your CMakeLists.txt you would add:

 add_test(NAME foo COMMAND ...)

and then use CTest for building and executing:

 ctest --build-and-test ...

More generally speaking and not considering the question of why you would like to do it - I think the best thing would be to just name and rely on concrete target dependencies instead of just taking ALL targets - I just wanted to add two possibilities to do what you wanted to do.

One would be to determine/track the list of all targets used as discussed here. This would look e.g. for library targets like this (getting your own/private GlobalTargetList):

macro(add_library _target)
    _add_library(${_target} ${ARGN})
    set_property(GLOBAL APPEND PROPERTY GlobalTargetList ${_target})
endmacro()

and use it at the end of your main CMakeLists.txt with

get_property(_allTargets GLOBAL PROPERTY GlobalTargetList)
add_dependencies(foo ${_allTargets})

Edit: Global BUILDSYSTEM_TARGETS property was released with CMake 3.7

The second - less favorable - approach does require that the foo target is not part of the ALL build (otherwise you end-up in an endless loop):

add_custom_target(foo)
set_target_properties(foo PROPERTIES EXCLUDE_FROM_ALL 1) 

add_custom_command(
    TARGET foo
    PRE_BUILD
    COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target ALL_BUILD --config $<CONFIGURATION>
)


标签: c++ c build cmake