gcc - 将两个 GCC 编译的 .o 目标文件合并到第三个 .o 文件中

标签 gcc compiler-construction linker ld object-files

如何将两个 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 GCcflags将在编译前合并源文件:

$ 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

最佳答案

-relocatable-r 传递给 ld 将创建一个适合作为 ld 输入的对象.

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

生成的文件与原始.o文件的类型相同。

$ 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

有关深入的解释,请参阅 MaskRay 的 Relocatable linking文章。

关于gcc - 将两个 GCC 编译的 .o 目标文件合并到第三个 .o 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980102/

相关文章:

c++ - C++中静态变量重定义错误

c++ - GCC 是否支持 long long int?

gcc - 如何强制 GCC 将 128 位/256 位结构作为 xmm/ymm 寄存器中的函数参数传递?

flash - 慢闪cs5编译

c# - 返回变量是由编译器自动创建的吗?

c++ - ld 的 -u 选项如何工作以及何时有用?

c++ - 如何使用已删除的复制构造函数初始化类数组(C++11)

linux - 执行附加在可执行文件末尾的机器代码

assembly - 是否有任何语言/编译器使用具有非零嵌套级别的 x86 ENTER 指令?

linker - FMDB : Linker command failed with exit code 1