Monday, April 11, 2022

[SOLVED] Escape special options in CMake

Issue

CMake use named arguments, but how to specify an argument which value is exactly the same as the name of the argument?

Example:

set(msg "COMMAND")
add_custom_command(TARGET tgt COMMAND echo ${msg})

will not work because ${msg} is interpreted as the name of the option, not the argument of the command echo. So it will execute echo without any argument.

Output: command ECHO activated. (on Windows)

Wanted output: COMMAND


Solution

CMake use named arguments

CMake does not use named arguments! It has argument lists and the command-specific "keywords" are merely delimiters for sublists of arguments.

For this specific command, you can use an always-true generator expression to "escape" it:

set(msg COMMAND)
add_custom_command(
  TARGET tgt
  COMMAND echo "$<1:${msg}>"
)

This works because the arguments are matched immediately during configure time (and $<1:COMMAND> is not the same as COMMAND), while the generator expression will be evaluated later, at generation time.



Answered By - Alex Reinking
Answer Checked By - Willingham (WPSolving Volunteer)