Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect the output of a CMake custom command to a file?

Tags:

I need to execute a command with add_custom_command a capture its stdout. The shell redirection to file > does not work and add_custom_command does not have any related options. How can I do it?

like image 579
tamas.kenez Avatar asked Jul 23 '15 08:07

tamas.kenez


2 Answers

(Please note that I changed my answer after investigating the issue because of Florian's comment. More about the edit below)

The documentation of the execute_process clearly states that it does not use intermediate shell, so redirection operators do not work there.

But it's not true for the add_custom_command. Redirection should work there as expected. [EDIT] The reason sometimes it does not seem to work is some unfortunate combination of the CMake generator, the VERBATIM specifier and the (missing) space between > and the file name.

It turned out if you make sure there's a space between > and the file name it works with in most cases, even with VERBATIM:

add_custom_command(OUTPUT ${some-file}
    COMMAND cmake --version > ${some-file}
    VERBATIM # optional
)

A note on an alternative solution: previously I thought add_custom_command, just like execute_process doesn't use an intermediate shell so I suggested calling a CMake script which contains an execute_process command which runs the actual command, redirecting its output with the OUTPUT_FILE option.

If for some reason the solution above still fails for you, try the alternative solution using an ExecuteProcessWrapper.cmake

like image 148
tamas.kenez Avatar answered Sep 20 '22 13:09

tamas.kenez


find_program(BASH bash HINTS /bin)
...
add_custom_command(
  OUTPUT
    ${some-file}
  COMMAND
    ${CMAKE_COMMAND} -E env ${BASH} -c "cmake --version > ${some-file} 2>&1"
  VERBATIM
)
like image 23
Lance E.T. Compte Avatar answered Sep 22 '22 13:09

Lance E.T. Compte