无法从 Windows 批处理脚本构建 C 程序

Cannot build C program from Windows batch script

我想使用 Windows 批处理脚本构建 C 程序,但编译器出现致命错误。

我有一台 Windows 10 电脑并使用 Microsoft C/C++ 编译器。

我是运行的批处理脚本叫build.bat内容是:

SET PROJECT_COMPILER=cl

SET HOME_DIRECTORY=%~dp0
SET PROJECT_SRC=%HOME_DIRECTORY%src\
SET PROJECT_BIN=%HOME_DIRECTORY%bin\
SET PROJECT_INCLUDE=%HOME_DIRECTORY%include\

%PROJECT_COMPILER% "%PROJECT_SRC%*.c" /I"%PROJECT_INCLUDE%" /link 
/out:"%PROJECT_BIN%out.exe"

del /f .\*.obj

我从行 %PROJECT_COMPILER% "%PROJECT_SRC%*.c" /I"%PROJECT_INCLUDE%" /link /out:"%PROJECT_BIN%out.exe" 得到的输出是:

C:\Users\Andrea Nardi\Documents\C project\test_project>cl "C:\Users\Andrea Nardi\Documents\C project\test_project\src\*.c"         
/I"C:\Users\Andrea Nardi\Documents\C project\test_project\include\" /link 
/out:"C:\Users\Andrea Nardi\Documents\C project\test_project\bin\out.exe"
Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25507.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

cl : Command line warning D9024 : unrecognized source file type 
'Nardi\Documents\C', object file assumed
 cl : Command line warning D9024 : unrecognized source file type 
 'project\test_project\bin\out.exe', object file assumed
 main.c
Microsoft (R) Incremental Linker Version 14.11.25507.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
Nardi\Documents\C
project\test_project\bin\out.exe
LINK : fatal error LNK1181: cannot open input file 'Nardi\Documents\C.obj'

看来是路径 C:\Users\Andrea Nardi\Documents\C project\ 中的 space 引起了您的问题。

通常避免在项目路径中使用 space,因为 space 是一个命令行,这将是各种 陷阱 的原因参数定界符。

使用 相对 路径也简单得多,这样您就可以从任何地方构建您的项目,而不是从一个非常特定的文件夹,同时避免 spaces。在这种情况下是这样的:

SET PROJECT_COMPILER=cl

REM Set working directory to that of this batch file
pushd %~dp0

REM Set paths relative to batch file path
SET PROJECT_SRC=.\src
SET PROJECT_BIN=.\bin
SET PROJECT_INCLUDE=.\include

REM Build...
%PROJECT_COMPILER% "%PROJECT_SRC%\*.c" /I"%PROJECT_INCLUDE%" /link 
/out:"%PROJECT_BIN%\out.exe"

REM  Clean-up...
del /f .\*.obj

REM Restore original working directory
popd