add_custom_command() POST_BUILD generator expression expansion not working

I want to run a POST_BUILD action after the build (but only in the Debug configuration).

After reading add_custom_command docs and a possible solution (here on Discourse) I understood that I can “wrap” my COMMAND into $<CONFIG:Debug> generator expression (to be sure it’s “empty” in Release mode).

I tried the following:

cmake_minimum_required(VERSION 3.18)

project(post-build CXX)
file(WRITE main.cxx "int main() {}")
add_executable(foo main.cxx)

  COMMAND $<$<CONFIG:Debug>:${CMAKE_COMMAND} -E echo "hi there from debug build">

But this gives me the CMake configure-time warnings and a hard failure during a build-time (using Ninja generator):

(...) && "$<1:C:\Program Files\CMake\bin\cmake.exe" -E echo "hi there from debug build" >""
[build] The system cannot find the path specified.
[build] ninja: build stopped: subcommand failed.
[build] Build finished with exit code 1

I tried many possible quotes combinations (including escaped quotes):
COMMAND $<$<CONFIG:Debug>:"${CMAKE_COMMAND} -E echo \"hi there from debug build\"">
COMMAND "$<$<CONFIG:Debug>:${CMAKE_COMMAND} -E echo \"hi there from debug build\">"

But even though it removed the configure-time warning, it still yields a hard error during the build-time.

Question: What would be the correct way to achieve what I want? Is it possible like this or there is a CMake limitation here?

(Note: if possible I’d like to keep the command to be executed as a whole, in one place. I am aware of other workarounds possible, as shown in the post mentioned at the beginning)

Spaces generally aren’t well-formed inside of genexes. You’ll need to replace the spaces with ; to make it parse properly (which is why you’re seeing half-expanded remnants in the build command).