Stefan
Stefan

Reputation: 4530

CMake add_custom_command: How to write a "quoted string" to a file?

I have spent way too much time trying to add a custom command that writes a "quoted string" to a file:

add_custom_command(
    OUTPUT file
    COMMAND ${CMAKE_COMMAND} -E echo "\"quoted string\"" > file
    ...
    DEPENDS something
    VERBATIM (?)
)

I have tried various ways to escape the quotes \", \\", \\\", quoting the whole command, putting the command in variable, but none of them worked. How can this be achieved?

Upvotes: 0

Views: 2230

Answers (1)

mydisplayname
mydisplayname

Reputation: 356

The following works on both Windows(Ninja) and WSL(unix makefiles):

set(my_output what_it_is.txt)
add_custom_command(
        OUTPUT ${my_output}
        COMMAND ${CMAKE_COMMAND} -E echo \"quoted string\" > ${my_output}
        VERBATIM
)

And the output:

$ cat some_bin/what_it_is.txt
"quoted string"

In my limited experience, VERBATIM is usually the key if you're fighting escaping things in custom commands.

Note: I believe that the redirect is platform specific, so you might want to consider doing something like the file command in a CMake script and invoking that script in the custom command, COMMAND ${CMAKE_COMMAND} -P some_script.cmake.

Upvotes: 4

Related Questions