如何在 Bash 中检查 gcc 是否失败、返回警告或成功?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1024525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if gcc has failed, returned a warning, or succeeded in Bash?
提问by Tyler
How would I go about checking whether gcc has succeeded in compiling a program, failed, or succeeded but with a warning?
我将如何检查 gcc 是否成功编译程序、失败或成功但有警告?
#!/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".
-n 表示“不为空”。
Thanks!
谢谢!
EDITIf it's not clear, this isn't working.
编辑如果不清楚,这不起作用。
回答by RichieHindle
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."
GCC 将在成功时返回零,或者在失败时返回其他内容。该行表示“如果最后一个命令返回的不是零。”
回答by Neil
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()).
您希望 bash 测试返回码,而不是输出。您的代码捕获标准输出,但忽略 GCC 返回的值(即 main() 返回的值)。
回答by nobody
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.
要区分完全干净的编译和有错误的编译,首先正常编译并测试 $?。如果非零,则编译失败。接下来,使用 -Werror(警告被视为错误)选项进行编译。测试 $? - 如果为 0,则编译时没有警告。如果非零,则编译时带有警告。
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

