如何在Windows批处理文件(cmd)中测试gcc是否未能编译程序?

3

我写了一段随机的 C 代码(app.c

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

还有这个批处理文件(run.bat

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

当我双击 run.bat 时,它会输出以下内容:
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 . . .

您可以注意到最后一个错误:
'app.exe' is not recognized as an internal or external command,
    operable program or batch file.

那是因为编译器未能成功编译,而没有了 app.exe。为了防止出现这种最后的错误,我想要检查 gcc 是否已经 成功,如果是,则 运行 app 。我在 SO 上搜索有关批处理程序中检查程序返回值的信息,然后了解到了一个名叫 errorLevel 的东西,所以我尝试使用它。这就是新的 run.bat 文件:
@echo off
:start
cls
echo Compiling...
gcc app.c -o app.exe
if %errorlevel% == 0
(
    cls
    app.exe
)
pause
goto start

在打印“Compiling...”后,它会立即退出应用程序,我猜可能是我的做法有误。

在Windows中,测试GCC是否未能编译程序的正确方法是什么?


应用程序 app.exe 是否与批处理文件在同一文件夹中?此外,将批处理文件命名为系统命令相同是非常不好的想法。run.bat 不是一个好的名称,建议改为 myrun.bat - Gerhard
是的,它们都在同一个目录中。好的,谢谢你提供的信息,我已经将其更改为compile.bat。:) 但它仍然立即退出... - Beyondo
应用程序.exe在运行时是否已编译?您能看到已完成的exe吗? - Gerhard
如果我从C文件中删除了ERROR;行,我只能看到已编译的exe,但在两种情况下它仍然立即退出... - Beyondo
1个回答

1
首先,请将您的文件重命名为myrun.bat而不是run.bat。让我们给gcc足够的时间来正确编译:
@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

最后,你的可执行文件实际上叫做app.exe还是包含空格的文件?例如my app.exe
根据我的评论,你可以启动gcc并等待它。
@echo off
:start
cls
echo Compiling...
start /b /w gcc app.c -o app.exe
app.exe
pause
goto start

最后,包含括号的if语句需要在同一行。else语句也是如此。因此,请更改以下内容:
if %errorlevel% == 0
(
    cls
    app.exe
)

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

这个可以运行,但是为什么我不必等待5秒钟(除非我想检查任何警告)。在这个例子中,没有必要。 - Beyondo
我添加了等待时间,仅仅是因为我可以看到在你想运行它的时候,app.exe还不存在。或者,启动并等待gcc。让我更新答案。 - Gerhard
see second example. - Gerhard
在查看了您代码中的if条件之后,我现在明白了问题,原来它是如此简单,同时也是微软的一个愚蠢错误... 在我发布的这个问题中的if条件中,我将两个大括号放在了不同的行上,而它所需要的只是将第一个大括号(放在if %errorlevel% == 0 行的末尾... 请注意,在(0之间应该有一个空格,这是微软的另一个愚蠢错误... 然后它就按预期工作了。您能否更新您的答案,以便我可以接受它? - Beyondo
在底部添加了一条注释。 - Gerhard
你添加的注释非常接近。因此,我将在你的答案中添加一段代码来解释我的意思,然后接受它(代码可以解释数百个单词?)。之后,你可以随意以自己的方式编辑你的答案。感谢你的帮助 :) - Beyondo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接