gcc共享库无法链接到glibc [英] gcc shared library failed linking to glibc

查看:920
本文介绍了gcc共享库无法链接到glibc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



代码有一个对 rand()的引用, < stdlib.h> 中的函数编译正常,但链接时报告链接器发生以下错误:

  gcc -shared -olibalg.so./sort.o 
/ usr / bin / ld:./sort.o:在创建共享对象时,无法使用未定义符号rand @@ GLIBC_2.2.5的重定位R_X86_64_PC32;使用-fPIC
/ usr / bin / ld重新编译:最终链接失败:错误值

sort.o是从文件编译的目标文件。 libalg.so是目标共享库名称。



任何人都可以解释为什么会发生这种情况吗?

感谢。

解决方案

关于 x86_64 架构 gcc 要求您使用 -fPIC p>

错误的根本原因是符号 rand 的重定位类型是类型 R_X86_64_PC32 这意味着它是PC相对的,应该位于 32bit 偏移量之内。



但是当前的体系结构是 x86_64 类型,这意味着它可以位于 64位地址空间内的任何位置。



所以动态链接器实际上不能将符号与这种重定位类型链接。



使用 -fPIC 或者使用 -mcmodel = large 编译你的代码,这实际上会使重定位类型变为 R_X86_64_64



有关如何完成链接的更多详细信息,请参阅这个伟大的博客由 Eli Bendersky

I'm writing a simple C shared library using Eclipse CDT under Linux 64bit.

The code has one reference to the rand() function in the <stdlib.h> It compiles fine but when linking it reports the following error from the linker:

gcc -shared -o "libalg.so"  ./sort.o   
/usr/bin/ld: ./sort.o: relocation R_X86_64_PC32 against undefined symbol `rand@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value

sort.o is the object file compiled from the file. libalg.so is the target shared library name.

Can anyone explaining why this happen?

Thanks.

解决方案

On x86_64 architecture gcc requires you to use -fPIC i.e Position Independent Code by default.

The underlying reason for the error is that the relocation type for the symbol rand is of type R_X86_64_PC32 which means that it is PC relative and should lie within 32bit offset from the following instruction.

But the current architecture is of x86_64 type which means that it can lie anywhere within the 64bit address space.

So the dynamic linker actually can not link a symbol with such a relocation type.

Either you have to use -fPIC or compile your code using the -mcmodel=large which will actually make the relocation type to R_X86_64_64.

For more details on how linking is done refer to this great blog by Eli Bendersky

这篇关于gcc共享库无法链接到glibc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆