gcc shared library failed linking to glibc

六眼飞鱼酱① 提交于 2019-12-30 01:23:05

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/21224090/gcc-shared-library-failed-linking-to-glibc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!