Link 使用 gcc 的一批目标文件数量未知

Link an unknown number of object files in a batch using gcc

我在目录中有未知数量的目标文件,所有这些文件都命名为 compile_to_cX.o ,其中 X 是从 1 到该目录中目标文件数的值。我想 link 他们使用 gcc,最终结果相当于:

  gcc -Xlinker -no-as-needed compile_to_c1.o ... compile_to_c1N.o -x none
  strip a.out

我尝试使用 fors 和环境变量,但 none 有效。 提前致谢

dir不带/b选项的运行时,它找到的文件数会显示在底部。由于您可以过滤 dir 文件扩展名,并且除了您想要的文件之外不会有其他 .o 文件,您可以简单地获取文件底部的文件计数字符串的第一个 space 分隔标记dir 输出。

从那里,您可以使用 for /L 循环构建一个字符串,其中包含您需要编译的所有文件。

@echo off
setlocal enabledelayedexpansion

:: Get the number of .o files from the dir listing
for /f "tokens=1" %%A in ('dir *.o^|find "File(s)"') do set o_files=%%A

:: Build a string with all of the .o files (up to 512 due to string length limitations)
for /L %%A in (1,1,!o_files!) do set "o_string=!o_string! compile_to_c%%A.o"

:: Run gcc and strip (remove the echos if your strings look correct)
echo gcc -Xlinker -no-as-needed !o_string! -x none
echo strip a.out
pause