Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch return value in CMake add_custom_command?

Tags:

cmake

how do I grab the return value of command invoked by add_custom_command?

I thought I could do something like this,

macro(mac param1)
    execute_process(COMMAND process ${param1} RESULT_VARIABLE res_var)
    if(${res_var} ....

endmacro(mac)

add_custom_command(COMMAND mac(param1))

but that won't work. I found out that even a plain

macro(mac)
endmacro()

add_custom_command(COMMAND mac())

does not work. Upon building, sh complains:

/bin/sh: 1: Syntax error: end of file unexpected

or, if I do not use the macro but call execute_process in add_custom_command itself:

/bin/sh: 1: Syntax error: word unexpected (expecting ")")

I guess that add_custom_command does not expect macros or built-in functions to be passed. However, how can I get the return value from the command in add_custom_command? Or, less specifically, how can I catch that the command in add_custom_command failed?

like image 290
Max Beikirch Avatar asked Mar 10 '13 13:03

Max Beikirch


1 Answers

The commands run by add_custom_command do not run until build time, so you can't "catch" that they failed during CMake's configure/generate steps.

If a custom command fails, then anything that depends on the output of that custom command will either be avoided, because make stops after that, or if make keeps going after errors, it will eventually return an error at its conclusion, and give some sort of "failed build" message.

You can always write an equivalent script that runs as a custom command, and then in that script, do something after certain types of errors. If you use cmake in -P script processing mode, you can make a cross platform script that calls execute_process and analyzes the return value.

For example:

configure_file(
  ${CMAKE_CURRENT_SOURCE_DIR}/script.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/script.cmake
  COPYONLY
)
add_custom_command(COMMAND ${CMAKE_COMMAND} -P
  ${CMAKE_CURRENT_BINARY_DIR}/script.cmake
)

And then in script.cmake.in:

execute_process(COMMAND process param1 RESULT_VARIABLE res_var)
if(NOT "${res_var}" STREQUAL "0")
  # do something here about the failed "process" call...
  message(FATAL_ERROR "process failed res_var='${res_var}'")
endif()
like image 74
DLRdave Avatar answered Oct 31 '22 12:10

DLRdave