问题描述
如何将两个 GCC 编译的 .o 目标文件合并为第三个 .o 文件?
How does one combine two GCC compiled .o object files into a third .o file?
$ 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 标志将在编译前合并源文件:
If you have access to the source files the -combine
GCC flag will merge the source files before compilation:
$ gcc -c -combine a.c b.c -o c.o
然而这仅适用于源文件,并且 GCC 不接受 .o
文件作为此命令的输入.
However this only works for source files, and GCC does not accept .o
files as input for this command.
通常,链接 .o
文件无法正常工作,因为您不能将链接器的输出用作它的输入.结果是一个共享库,并没有静态链接到生成的可执行文件中.
Normally, linking .o
files does not work properly, as you cannot use the output of the linker as input for it. The result is a shared library and is not linked statically into the resulting executable.
$ 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
推荐答案
将 -relocatable
或 -r
传递给 ld
将创建一个对象适合作为 ld
的输入.
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
生成的文件与原始.o
文件的类型相同.
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
这篇关于将两个 GCC 编译的 .o 目标文件合并到第三个 .o 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!