如何检查gcc在Bash中是否失败、返回警告或成功?
我该如何检查gcc是否成功编译了程序、是否失败或是否成功但有警告如何检查gcc在Bash中是否失败、返回警告或成功?,bash,gcc,Bash,Gcc,我该如何检查gcc是否成功编译了程序、是否失败或是否成功但有警告 #!/bin/sh string=$(gcc helloworld.c -o helloworld) if [ string -n ]; then echo "Failure" else echo "Success!" fi 这只会检查它是否成功(失败或编译时出现警告) -n表示“不为空” 谢谢 编辑如果不清楚,则此操作无效 if gcc helloworld.c -o helloworld; then e
#!/bin/sh
string=$(gcc helloworld.c -o helloworld)
if [ string -n ]; then
echo "Failure"
else
echo "Success!"
fi
这只会检查它是否成功(失败或编译时出现警告)
-n表示“不为空”
谢谢
编辑如果不清楚,则此操作无效
if gcc helloworld.c -o helloworld; then
echo "Success!";
else
echo "Failure";
fi
您希望bash测试返回代码,而不是输出。您的代码捕获标准输出,但忽略GCC返回的值(即main()返回的值)。您的条件应该是:
if [ $? -ne 0 ]
GCC将在成功时返回零,或者在失败时返回其他值。该行显示“如果最后一个命令返回的不是零。”要区分完全干净编译和有错误编译,请首先正常编译并测试$?。如果非零,则编译失败。接下来,使用-Werror(警告被视为错误)选项编译。测试$?-如果为0,则编译时不会出现警告。如果非零,则编译时会显示警告 例:
或者,在单独的shell脚本行中运行gcc,然后测试$?。它不可能工作的另一个原因是:正确的语法是
[-n“$string”]
。请注意,即使出现警告,gcc也会返回退出代码0。如果必须考虑警告,Werror会有所帮助。此暴力强制包括两个编译。如果您真的想这样做,那么第二次运行应该只包含-fsyntax
(除了解析完整的代码外,没有其他内容了)。在任何情况下,附加检查gcc
s输出的选项(将其标准输出存储在临时文件中,并为arning
[w可能是大写还是不大写])可能是更好的解决方案。$?如果有人不知道,则表示上次运行命令的返回值
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