是否可以从gcc中的其他目标文件创建目标文件?

Car*_*ers 3 linker gcc makefile

我试图在makefile中做这样的事情:

program.exe: ui.o main.o
   gcc ......etc
ui.o: window1.o window2.o
   gcc -c window1.o window2.o -o ui.o #this doesn't want to work
window1.o: window1.c window1.h window1_events.c window1_controls.c ...
   gcc -c window1.c window1_events.c window1_controls.c... -o window1.o
window2.o: ...
   gcc ...
main.o: ...
   gcc ...
Run Code Online (Sandbox Code Playgroud)

但是当我像这样编译时,它会给出错误"输入文件未使用,因为链接未完成",然后我得到一堆未解决的外部等等 - 通过更改解决的问题

program.exe: ui.o main.o
   gcc ...
Run Code Online (Sandbox Code Playgroud)

program.exe: window1.o window2.o main.o
   gcc ...
Run Code Online (Sandbox Code Playgroud)

那么是否可以将目标文件链接在一起,以避免在makefile中有长达一英里的行并且稍微分解构建过程?

Emp*_*ian 17

是:要将多个目标文件合并为一个,请使用ld -rld -Ur:

来自Linux上的"man ld":

   -r
   --relocatable
      Generate  relocatable  output---i.e.,  generate  an output file that can
      in turn serve as input to ld.  This is often called partial linking.
      As a side effect, in environments that support standard Unix magic
      numbers, this option also sets the output file’s magic number to
      "OMAGIC".
      If this option is not specified, an absolute file is produced.
      When linking C++ programs, this option will not resolve references to
      constructors;  to do that, use -Ur.
Run Code Online (Sandbox Code Playgroud)

你也可以用gcc做到这一点:

gcc -Wl,-r foo.o bar.o -o foobar.o -nostdlib
Run Code Online (Sandbox Code Playgroud)

像这样合并目标文件比使用归档库有一些优势:如果合并文件很少更改(比如main.c),那么最终的可执行链接会更快.

OTOH,使用归档库,链接器将只使用它所需的东西,因此如果例如window2.c最终没有必要,你的可执行文件可能会变小.


小智 9

我的一堆目标文件是一个库.您可以使用ar 实用程序创建库.以下示例创建一个名为mylib.a的库,其中包含文件foo.o和bar.o

ar rvs mylib.a foo.o bar.o
Run Code Online (Sandbox Code Playgroud)

然后,您可以在编译器命令行上使用它来链接它:

gcc -o myexe main.c mylib.a
Run Code Online (Sandbox Code Playgroud)