CMake: How to add a custom command that only runs for one coniferation?
I want to add a custom cmake command that only runs when a custom target is created in the Debug config when using a generator with multiple Visual Studio configurations. Is there a clean way to do this?
To implement this, I first tried to wrap the entire command list in a generator expression like this.
add_custom_command(
...
COMMAND $<$<CONFIG:Debug>:cmake;-E;echo;foo>
)
But it gives me a syntax error when I execute the command. After some trial errors, I got the following hacky solution to work. This wraps each word from 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, >
)
Runs the command cmake -E echo foo
when compiling the Debug configuration and dummy command echo " " " " " "
for all other configurations.
This is pretty ugly and the stub command needs to be changed depending on the host system. On Linux it might be ":" ":" ":" ":"
. So is there a cleaner way to do this?
Thank you for your time!
Here is my piece of code (tested on multiple platforms with one and multiple configurations):
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: the COMMAND_EXPAND_LISTS
keyword is only available with CMake version> = 3.8
Link
- Modern way of setting compiler flags in a cross platform cmake project