[CMake] Executing processes as part of a COMMAND option in add_custom_command

Michael Hertling mhertling at online.de
Thu Apr 14 10:26:44 EDT 2011


On 04/14/2011 12:44 PM, J.S. van Bethlehem wrote:
> Dear users,
> 
> As a new user CMake I've come across some things I don't fully 
> understand yet. Here is such a thing:
> when I build documentation, I want to run some files from a  'demo' 
> subdirectory and create output - suppose the (binary) file is called 
> 'func1_demo', then in my old Makefiles I used to do:
>  ./func1_demo >& func1_demo.out
>  I implemented this in CMake using a special 'RunCommand.cmake' script 
> that does:
>    execute_process(COMMAND ${dbin} OUTPUT_FILE ${dbin_out} ERROR_FILE 
> ${dbin_out})
> and the CMakeLists.txt file that creates the demos, has
>   ${CMAKE_COMMAND} -Ddbin="./${demo_name}" -Ddbin_out="${demo_name}.out" 
> -P RunCommand.cmake
> as the COMMAND part of an add_custom_command. It seems a bit contrived, 
> having to pass these variables through the command line to a separate 
> file. Is there a better way to do this?

You might incorporate the variables in your script; e.g., provide
a RunCommand.cmake.in template which contains the following lines

EXECUTE_PROCESS(
    COMMAND @dbin@
    OUTPUT_FILE @dbin_out@
    ERROR_FILE @dbin_out@
)

and use CONFIGURE_FILE(RunCommand.cmake.in RunCommand.cmake @ONLY) to
generate the actual script to be used. However, the "variables" won't
be variable anymore, and the script will be useful for one case only.

Alternatively, you might rely on environment variables in your script

EXECUTE_PROCESS(
    COMMAND $ENV{dbin}
    OUTPUT_FILE $ENV{dbin_out}
    ERROR_FILE $ENV{dbin_out}
)

but these must be defined when the custom command is run. In the end,
your initial approach with -Dvar=val is reliable and flexible and to
be preferred, IMO, although it's possibly not the most aesthetic one.

BTW, does a direct approach like

ADD_CUSTOM_COMMAND(OUTPUT... COMMAND ${demo_name} >& ${demo_name}.out)

work for you? If so, note that it's not really portable due to the ">&".

Regards,

Michael


More information about the CMake mailing list