Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 585
Knitschi Avatar asked Aug 02 '17 08:08

Knitschi


1 Answers

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

  • Modern way to set compiler flags in cross-platform cmake project
like image 96
Florian Avatar answered Oct 06 '22 21:10

Florian