Write multiline text to file with path given by generator expression

Hi,

I have a project that requires creating a text file in the same folder as the output binary. The location of the binary can be obtained using a generator expression, which is not available when using file(WRITE). However, if I use something like

add_custom_command(TARGET tgt
  POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E echo ${text_to_write} > $<TARGET_FILE_DIR:tgt>/qt.conf)

the ninja generator complains at build time, even if I use VERBATIM. The text has multiple lines as is something like this:

[Paths]
Plugins = /home/user/path/to/qt5/plugins

The best solution that I’ve found is to use file(WRITE) to a temp file, then copying the temp file to its final destination using add_custom_command(), but it feels too convoluted. Is there a way of doing this with just one command?

You probably want file(GENERATE), which can use generator expressions but writes the file during the CMake generation phase:

file(GENERATE
    OUTPUT "$<TARGET_FILE_DIR:tgt>/qt.conf"
    CONTENT "${text_to_write}"              # Use one of these two
    #INPUT "/path/to/somewhere/qt.conf"     #
)
1 Like