-->

Is -fPIC for shared libraries ONLY?

2020-07-17 06:53发布

问题:

I know -fPIC is necessary for shared libraries and know why.

However, I am not clear on the question:

Should -fPIC never be used during building an executable or a static library?

回答1:

Should -fPIC never be used during building an executable or a static library?

Never is a strong word, and the statement above is false.

Code built with -fPIC is (slightly) less optimal, so why would you want to put it into anything other than a shared library?

Let's start with a static library, which has an easy answer.

Suppose you want to give your users a static library that can be linked into either an executable, or into a shared library of their own?

In that case you must either give them 3 separate archive libraries (one built with -fPIC for linking into shared libraries, one built with -fPIE for linking into PIE executables, and a "regular" one), or you can give them a single archive library (which must have code built with -fPIC).

Now, it could be argued that you should instead give them a shared library, but that forces your end users to distribute 2 binaries, and they may prefer to not do that.

But suppose you want to build a regular (non-PIE) executable. What could be the reason to link in -fPIC code into such executable?

Well, suppose you are in the development stage, and don't care that much about optimizing the code yet. Suppose further that you want to test your code as both a shared library, and as part of PIE and non-PIE executable.

Under above conditions, you could either compile your code 3 times (with and without -fPIC, and with -fPIE), or you could compile it once (with -fPIC) and link it into all 3 of shared library, PIE and non-PIE executable. Doing this saves a lot of compilation time, and some build system complexity.

TL;DR: putting -fPIC objects into executables and static libraries has its place, and you should understand the reason why you are doing it (if you end up doing it).

Update:

Code in an object file is always relocatable

Correct.

is it position-independent code?

No: not all relocatable code is position-independent.

Position-independent code is a subset of relocatable code. Relocatable code can have relocations that apply to any section. Position-independent code must not have any relocations against .text (and .rodata).