cmakecmake-custom-command

CMake: How to add a custom command that is only executed for one configuration?


I want to add a cmake custom command that is only executed when the custom target is build in the Debug configuration while using the Visual Studio multi-config generator. Is there a clean way to do this?

In order to implement this, I first tried wrapping the whole command list in a generator expression like this.

add_custom_command(
    ...
    COMMAND $<$<CONFIG:Debug>:cmake;-E;echo;foo>
)

But this gives me a syntax error when the command is executed. After some trial-and-error I got the following hacky solution to work. This wraps each word of the command list in a generator expression like this.

add_custom_command(
    ...
    COMMAND $<IF:$<CONFIG:Debug>,cmake,echo>;$<IF:$<CONFIG:Debug>,-E, >;$<IF:$<CONFIG:Debug>,echo, >;$<IF:$<CONFIG:Debug>,foo, >
)

This executes the cmake -E echo foo command when compiling the Debug configuration and the dummy command echo " " " " " " for all other configurations.

This is quite ugly and the dummy command must be changed depending on the host system. On Linux it could be ":" ":" ":" ":". So Is there a cleaner way to do this?

Thank you for your time!


Solution

  • Here is my piece of code (tested on several single- and multi-configuration platforms):

    CMakeLists.txt

    cmake_minimum_required(VERSION 3.8)
    
    project(DebugEchoFoo NONE)
    
    string(
        APPEND _cmd
        "$<IF:$<CONFIG:Debug>,"
            "${CMAKE_COMMAND};-E;echo;foo,"
            "${CMAKE_COMMAND};-E;echo_append"
        ">"
    )
    
    add_custom_target(
        ${PROJECT_NAME}
        ALL
        COMMAND "${_cmd}"
        COMMAND_EXPAND_LISTS
    )
    

    Note: COMMAND_EXPAND_LISTS is keyword is only available with CMake version >= 3.8

    Reference