2
votes

Please somebody help. I am creating a shared library and when run with this command this gives a error "gcc -shared libx.o -o libx.so"

/usr/lib64/gcc/x86_64-suse-linux/4.3/../../../../x86_64-suse-linux/bin/ld: libx.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC libx.o: could not read symbols: Bad value

collect2: ld returned 1 exit status

So, I run it with -FPIC, it compiles, please can you give me a good understanding of -FPIC significance at the memory level, I mean how it is shared in the physical memory between 2 programs using this shared library.

Thanks a lot.

2
Possible duplicate of GCC -fPIC optionPhilipp Claßen

2 Answers

1
votes

-fpic stands for position independent code.

you can read drepper to get more idea on dynamic linking http://www.akkadia.org/drepper/dsohowto.pdf

Seems a duplicate of similar post GCC -fPIC option

1
votes

For systems with virtual memory the loader is likely to map the shared code into some contiguous pages in the memory space of the applications that are using that library. In order to share these pages between multiple processes they must be:

  1. read-only.
  2. able to be mapped at an arbitrary in the address space of a process.

consequences:

  1. Most code is not read-only in that it can not just be mapped into the memory space of a process and run - it must first be modified by the loader in ways that are specific to each process. In order to achieve read-only text you pass the -fpic option to the compiler. This causes the compiler to generate less optimal machine code but with the benefit that it is readonly.

  2. Efficient code can often not be mapped to an arbitrary location in the address space. Commonly efficient code is either constrained to a particular address, or to a low range of addresses. The -fpic options instructs the compiler to use less efficient code gen but with the benefit of not having a constraint about where it is run.

Now we can understand your problem:

relocation R_X86_64_32 against `.rodata' - Here the linker is warning you that the compiler has used codgen that is constrained run in to a low range of addresses. Therefore, it is unsuitable for use in a shared library.