Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc shared library failed linking to glibc

Tags:

c

gcc

linker

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.

like image 358
Wudong Avatar asked Jan 19 '14 23:01

Wudong


1 Answers

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

like image 79
abhi Avatar answered Nov 03 '22 01:11

abhi