10

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.

Suraj
  • 67
  • 9
Tyler
  • 4,679
  • 12
  • 41
  • 60

3 Answers3

20

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
  • 272,464
  • 47
  • 358
  • 399
  • 2
    $? means return value of last ran command if anyone doesn't know – Lightsout Apr 25 '18 at 20:35
  • [Why is testing `$?` to see if a command succeeded or not an antipattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Jun 20 '22 at 15:22
18
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()).

How Chen
  • 1,340
  • 2
  • 17
  • 37
Neil
  • 2,378
  • 1
  • 20
  • 28
12

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
nobody
  • 19,814
  • 17
  • 56
  • 77
  • This brute forcing includes two compilations. If you really want to go that way the second run should include `-fsyntax-only` (there won't be anything more than parsing the complete code). In any case the option to additional check `gcc`s output (storing its stdout in a temporary file and grep for `arning` [the w may be in uppercase or not]) is likely the better solution. – Simon Sobisch May 05 '17 at 20:25
  • `if ! gcc -Wall -o foo foo.c; then echo "Compile failed!"; exit 1; fi` -- no reason to use `$?` at all. `[ $? -eq 0 ]` is generating a _second_ `$?` (that of the `[` command) and testing that; why not just test the `$?` of the `gcc` command directly? – Charles Duffy Jun 20 '22 at 15:23