What happens if I just drop the
-fPIC
when compiling a.so
-file?
The resulting shared object ELF file would (very probably) be dynamically loaded at semi-random (i.e. unpredictable) page addresses (e.g. because the mmap
syscall will encounter ASLR).
And the linker would produce a huge lot of relocation operations. So the dynamic linker (ld.so
) would have to slowly process a big lot of relocations, so your text segment would have to be rewritten (and won't be efficiently read-only shared with other processes using the same .so
file).
So in practice forgetting the -fPIC
on a shared object (i.e. dynamically linked library) is most often a bad idea, even if it is possible.
Read Drepper's HowTo do Dynamic Shared Libraries paper and Wheeler's Program Library Howto
BTW, position independent code is much more costly on x86 (32 bits) than on x86-64. But it is worth the effort (probably, PIC code is at most 5 to 10% slower than non-PIC on x86 32 bits).