将两个GCC编译的.o目标文件合并到第三个.o文件中(combine two GCC compiled .o object files into a third .o file)

其他开发 IT屋
百度翻译此文   有道翻译此文
问 题

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

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

However this only works for source files, and GCC does not accept .o files as input for this command.

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
解决方案

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

$ ld -r 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

本文地址:IT屋 » combine two GCC compiled .o object files into a third .o file

问 题

如何将两个GCC编译的.o目标文件合并到第三个.o文件中?



  $ gcc -c ac -o ao 
$ gcc -c bc -o bo
$? ao bo -o co
$ gcc co other.o -o executable


访问源文件 -combine GCC标志将在编译之前合并源文件:



  $ gcc -c -combine ac bc -o co 


源文件,GCC不接受 .o 文件作为此命令的输入。



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



  $ gcc -shared ao bo -o co 
$ gcc co other.o -o executable
$ ./executable
./executable:加载共享库时出错:co:无法打开共享对象文件:没有这样的文件或目录
$ file co
co:ELF 32位LSB共享对象,Intel 80386,版本1(SYSV),动态链接,未剥离
$文件ao
ao:ELF 32位LSB可重定位,英特尔80386版本1(SYSV),未剥离

解决方案

将 -r (或 - 可重新定位)传递到 ld 将创建一个适合作为 ld 输入的对象。



  $ ld -r ao bo -o co 
$ gcc co other.o -o executable
$ ./executable


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



  $ file ao 
ao:ELF 32位LSB可重定位,Intel 80386,版本1(SYSV),未剥离
$文件co
co:ELF 32位LSB可重定位,Intel 80386,版本1(SYSV),未剥离

本文地址:IT屋 » 将两个GCC编译的.o目标文件合并到第三个.o文件中

官方微信
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起