3

I'm building a shared library. I need only one function in it to be public.

The shared library is built from a few object files and several static libraries. The linker complains that everything should be build with -fPIC. All the object files and most static libraries were built without this option.

This makes me ask a number of questions:

  1. Do I have to rebuild every object file and every static library I need for this dynamic lib with -fPIC? Is it the only way?

  2. The linker must be able to relocate object files statically, during linking. Correct? Otherwise if object files used hardcoded constant addresses they could overlap with each other. Shouldn't this mean that the linker has all the information necessary to create the global offset table for each object file and everything else needed to create a shared library?

  3. Should I always use -fPIC for everything in the future as a default option, just in case something may be needed by a dynamic library some day?

I'm working on Linux on x86_64 currently, but I'm interested in answers about any platform.

Blue Nebula
  • 932
  • 4
  • 9

1 Answers1

2
  1. You did not say which platform you use but on Linux it's a requirement to compile object files that go into your library as position independent code (PIC). This includes static libraries at least in practice.

  2. Yes. See load time relocation of shared libraries and position independent code pic in shared libraries.

  3. I only use -fPIC when compiling object files that go into libraries to avoid unecessary overhead.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • I'm working on Linux on x86_64. I modified the question to add it. I'll read the articles you linked and reply or approve your answer later when I'm done :) – Blue Nebula Apr 03 '21 at 15:26
  • About your 3rd point: what do you do when you need to build both a binary and a shared library using some common files? Do you compile all those object files twice, once with PIC and once without? – Blue Nebula Apr 04 '21 at 08:02
  • @BlueNebula yes, but I think you need to ask yourself, why duplicate the code in your application? – Allan Wind Apr 04 '21 at 10:54
  • the code is not duplicated. Only the compiled stuff is. At the beginning I only needed to build a binary for my application and nothing else. But now I need to provide a plugin for a different application, where my plugin does parts of what my binary does. How would you do this? – Blue Nebula Apr 05 '21 at 07:04
  • Use the plugin in your app, too. – Allan Wind Apr 05 '21 at 07:20