Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check exit status of `execute_process` in cmake

Tags:

cmake

In my cmake file i run a command with execute_process. And i want to check if it failed. It doesn't print anything to stderr.

So far I have been using a bash script that runs the command and then checks the exit status with $? == 1.

Is there a way to do something similar with cmake?

execute_process(COMMAND "runThis")
if("{$?}" EQUAL 1)
    message( FATAL_ERROR "Bad exit status")
endif()

I use cmake 3.12.1

like image 837
user2393256 Avatar asked Aug 29 '18 12:08

user2393256


3 Answers

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()
like image 79
Tsyvarev Avatar answered Nov 19 '22 15:11

Tsyvarev


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
like image 40
caldfir Avatar answered Nov 19 '22 16:11

caldfir


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)
like image 3
Mila Nautikus Avatar answered Nov 19 '22 15:11

Mila Nautikus