tags:

views:

285

answers:

3

Hi. How would I go about checking whether gcc has succeeded in compiling a program, failed, or succeeded but with a warning?

#!/bin/sh

string=$(gcc helloworld.c -o helloworld)

if [ string -n ]; then
    echo "Failure"
else
    echo "Success!"
fi

This only checks whether it has succeeded or (failed or compiled with warnings).

-n means "is not null".

Thanks!

EDIT If it's not clear, this isn't working.

+2  A: 

if gcc helloworld.c -o helloworld; then echo "Success!"; else echo "Failure"; fi

You want bash to test the return code, not the output. Your code captures stdout, but ignores the value returned by GCC (ie the value returned by main()).

Neil
Alternatively, run gcc in a separate shell script line, then test $?.
Martin v. Löwis
+6  A: 

Your condition should be:

if [ $? -ne 0 ]

GCC will return zero on success, or something else on failure. That line says "if the last command returned something other than zero."

RichieHindle
+2  A: 

To tell the difference between compiling completely cleanly and compiling with errors, first compile normally and test $?. If non-zero, compiling failed. Next, compile with the -Werror (warnings are treated as errors) option. Test $? - if 0, it compiled without warnings. If non-zero, it compiled with warnings.

Ex:

gcc -Wall -o foo foo.c
if [ $? -ne 0 ]
then
    echo "Compile failed!"
    exit 1
fi

gcc -Wall -Werror -o foo foo.c
if [ $? -ne 0 ]
then
    echo "Compile succeeded, but with warnings"
    exit 2
else
    echo "Compile succeeded without warnings"
fi
Andrew Medico