将两个 GCC 编译的.o 对象文件合并到第三个.o 文件中

如何将两个 GCC 编译的.o 对象文件组合成第三个.o 文件?

$ gcc -c  a.c -o a.o
$ gcc -c  b.c -o b.o
$ ??? a.o b.o -o c.o
$ gcc c.o other.o -o executable

如果你可以访问源文件,-combine GCC 标志会在编译之前合并源文件:

$ gcc -c -combine a.c b.c -o c.o

但是,这只适用于源文件,并且 GCC 不接受 .o文件作为此命令的输入。

通常,链接 .o文件不能正常工作,因为您不能使用链接器的输出作为输入。结果是一个共享库,不会静态链接到生成的可执行文件中。

$ gcc -shared a.o b.o -o c.o
$ gcc c.o other.o -o executable
$ ./executable
./executable: error while loading shared libraries: c.o: cannot open shared object file: No such file or directory
$ file c.o
c.o: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, not stripped
$ file a.o
a.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
61852 次浏览

If you want to create an archive of two or more .o files (i.e.. a static library) use the ar command:

ar rvs mylib.a file1.o file2.o

Passing -relocatable or -r to ld will create an object that is suitable as input of ld.

$ ld -relocatable a.o b.o -o c.o
$ gcc c.o other.o -o executable
$ ./executable

The generated file is of the same type as the original .o files.

$ file a.o
a.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
$ file c.o
c.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped