Check exit status of `execute_process` in cmake

You may find exit status of the executing process by using RESULT_VARIABLE option for execute_process invocation. From option's documentation:

The variable will be set to contain the result of running the processes. This will be an integer return code from the last child or a string describing an error condition.

Example:

execute_process(COMMAND "runThis" RESULT_VARIABLE ret)
if(ret EQUAL "1")
    message( FATAL_ERROR "Bad exit status")
endif()

The documentation indicates that RESULT_VARIABLE may be used to check the status of execute_process. Since it may contain either a string or an exit-code, both should be considered when checking for errors.

Here is an example putting that into practice:

# good
execute_process(
  COMMAND cmake --version
  RESULT_VARIABLE STATUS
  OUTPUT_VARIABLE OUTPUT1 
  ERROR_QUIET )
if(STATUS AND NOT STATUS EQUAL 0)
  message(STATUS "FAILED: ${STATUS}")
else()
  message(STATUS "SUCCESS: ${OUTPUT1}")
endif()

# nonzero exit code
execute_process(
  COMMAND cmake -G xxxx
  RESULT_VARIABLE STATUS
  OUTPUT_VARIABLE OUTPUT2 
  ERROR_QUIET )
if(STATUS AND NOT STATUS EQUAL 0)
  message(STATUS "FAILED: ${STATUS}")
else()
  message(STATUS "SUCCESS: ${OUTPUT2}")
endif()

# bad command
execute_process(
  COMMAND xxxx
  RESULT_VARIABLE STATUS
  OUTPUT_VARIABLE OUTPUT3 
  ERROR_QUIET )
if(STATUS AND NOT STATUS EQUAL 0)
  message(STATUS "FAILED: ${STATUS}")
else()
  message(STATUS "SUCCESS: ${OUTPUT3}")
endif()

output:

SUCCESS: cmake version 3.18.0-rc3

CMake suite maintained and supported by Kitware (kitware.com/cmake).

FAILED: 1
FAILED: The system cannot find the file specified

cmake execute_process, exit on error

since cmake 3.19 we have the option COMMAND_ERROR_IS_FATAL

execute_process(COMMAND echo hello COMMAND_ERROR_IS_FATAL ANY)

Tags:

Cmake