How to test if gcc has failed to compile a program in Windows Batch File (cmd)?

Viewed 1007

I have made this random C code (app.c)

int main()
{
    ERROR; // Just a random code to make sure the compiler fails.
}

and this batch file (run.bat)

@echo off
:start
cls
echo Compiling...
gcc app.c -o app.exe
app.exe
pause
goto start

When I double-click run.bat, it gives me the following output:

Compiling...
app.c: In function 'main':
app.c:3:2: error: 'ERROR' undeclared (first use in this function)
  ERROR; // Just a random code to make sure the compiler fails.
  ^~~~~
app.c:3:2: note: each undeclared identifier is reported only once for each function it appears in
'app.exe' is not recognized as an internal or external command,
operable program or batch file.
Press any key to continue . . .

You can notice the last error:

'app.exe' is not recognized as an internal or external command,
    operable program or batch file.

That's because there's no app.exe since the compiler has failed to compile it. To prevent that last error from happening, I wanted to check if gcc has succeeded and if so, run the app.

I searched in SO about checking the return values of a program in Batch and then I learned a thing called errorLevel so I tried to use it.

and this is the new run.bat file:

@echo off
:start
cls
echo Compiling...
gcc app.c -o app.exe
if %errorlevel% == 0
(
    cls
    app.exe
)
pause
goto start

It immediately exits the app after printing 'Compiling...', I guess I do it wrong maybe..

What's the right way to test if GCC has failed to compile a program in Windows?

1 Answers

Firstly, please rename your file to myrun.bat and not run.bat. Let's give gcc time to compile properly:

@echo off
:start
cls
echo Compiling...
gcc app.c -o app.exe
timeout 5
:wait
if exist app.exe (app.exe) else (timeout 5 && goto wait)
pause
goto start

Lastly, is your executable actually called app.exe or is it a file containing whitespace? i.e my app.exe

As per my comment, you can start gcc and wait for it.

@echo off
:start
cls
echo Compiling...
start /b /w gcc app.c -o app.exe
app.exe
pause
goto start

Lastly. If statements containing parenthesis needs to be on the same line. As well as for else statements. So change:

if %errorlevel% == 0
(
    cls
    app.exe
)

To

if %errorlevel% == 0 (
    cls
    app.exe
)
Related