The most often mistake is using %ERRORLEVEL%
in a command block starting with (
and ending with matching )
.
The entire command block is preprocessed by Windows command interpreter before running any command in the command block or the IF or FOR command usually used on line with opening (
. During this preprocessing all %variable%
references are replaced by current values of the referenced environment variables. Then the command block is executed with the preprocessed code.
This behavior can be seen by removing @echo off
at top of the batch file, or modify it to @echo on
or rem @echo off
and run the batch file from within a command prompt window. Now Windows command interpreter outputs to console window every command line and command block after preprocessing as really executed next.
The help of command SET output on running set /?
in a command prompt window explains on an IF and a FOR example how to reference an environment variable within a command line or command block modified in same command line or command block on execution using delayed environment variable expansion.
But for this case there is no need for %ERRORLEVEL%
expanded during preprocessing phase or delayed expanded using !ERRORLEVEL!
at all.
There is the good old IF ERRORLEVEL X ...
syntax working since MS-DOS up to currently latest Windows 10.
CMake exits with exit code 0
on success and a greater number on error as nearly all console applications.
IF ERRORLEVEL X ...
means IF exit code (return value of function main
) assigned to environment variable ERRORLEVEL
is greater or equal X
THEN ...
Then I suggest to look on:
A successful IF does not modify value of ERRORLEVEL
. And EXIT /B
without a number also does not modify ERRORLEVEL
.
So on next line after the command line running CMake there is only this command line needed to exit the processing of current batch file and return to calling batch file or process on any error encountered by CMake:
if errorlevel 1 exit /B
The calling batch file or process gets the exit code of CMake as a result of the batch file execution because IF and EXIT don't modify ERRORLEVEL
in this case. It's really so easy!