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

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

问题描述

我正在使用 Eclipse CDT 在 Linux 64bit 下编写一个简单的 C 共享库.

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

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

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 是从文件编译的目标文件.libalg.so 是目标共享库名称.

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

谁能解释为什么会这样?

Can anyone explaining why this happen?

谢谢.

推荐答案

关于x86_64架构gcc需要你使用-fPIC即位置默认独立代码.

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

错误的根本原因是符号 rand 的重定位类型是 R_X86_64_PC32 类型,这意味着它是 PC 相关的,应该位于 内32bit 与下一条指令的偏移量.

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.

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

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.

您必须使用 -fPIC 或使用 -mcmodel=large 编译代码,这实际上会将重定位类型设置为 R_X86_64_64.

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.

有关如何完成链接的更多详细信息,请参阅 Eli Bendersky

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

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

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