I'm writing a simple C shared library using Eclipse CDT under Linux 64bit.
我在Linux 64bit下使用Eclipse CDT编写一个简单的C共享库。
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.
排序。o是从文件中编译的对象文件。libalg。目标共享库名称也是如此。
Can anyone explaining why this happen?
有人能解释一下为什么会这样吗?
Thanks.
谢谢。
1 个解决方案
#1
8
On x86_64
architecture gcc
requires you to use -fPIC
i.e Position Independent Code by default.
在x86_64体系结构上,gcc要求您使用-fPIC i。e位置独立的代码默认。
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.
出现错误的根本原因是符号rand的重新定位类型为R_X86_64_PC32,这意味着它是PC的亲戚,应该位于与以下指令的32位偏移量之间。
But the current architecture is of x86_64
type which means that it can lie anywhere within the 64bit
address space.
但是当前的架构是x86_64类型,这意味着它可以位于64位地址空间中的任何位置。
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
.
要么使用-fPIC,要么使用-mcmodel=large编译代码,这实际上会将重新定位类型设置为R_X86_64_64。
For more details on how linking is done refer to this great blog by Eli Bendersky
有关链接是如何完成的更多细节,请参考Eli Bendersky的这个伟大的博客
#1
8
On x86_64
architecture gcc
requires you to use -fPIC
i.e Position Independent Code by default.
在x86_64体系结构上,gcc要求您使用-fPIC i。e位置独立的代码默认。
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.
出现错误的根本原因是符号rand的重新定位类型为R_X86_64_PC32,这意味着它是PC的亲戚,应该位于与以下指令的32位偏移量之间。
But the current architecture is of x86_64
type which means that it can lie anywhere within the 64bit
address space.
但是当前的架构是x86_64类型,这意味着它可以位于64位地址空间中的任何位置。
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
.
要么使用-fPIC,要么使用-mcmodel=large编译代码,这实际上会将重新定位类型设置为R_X86_64_64。
For more details on how linking is done refer to this great blog by Eli Bendersky
有关链接是如何完成的更多细节,请参考Eli Bendersky的这个伟大的博客