Search code examples
c++clinuxcompilation

What is the relationship among PIC/PIE, no-PIC/no-PIE, statically linked executable and dynamically linked executable in the case of gcc?


After some searching on Internet, I realize that:

  1. PIC and PIE is the same concept. If this is correct, I would like to use PIC to stand for PIC/PIE.
  2. PIC seems to be an "Attribute" of binary code, which type of binary code can be executed regardless of which memory location it's loaded into. Is it correct?
  3. PIC/no-PIC have no strong relationship with statically/dynamically linked executable. We can combine PIC/non-PIC with statically/dynamically linked executable in any way theoretically. I have noticed some interesting options in gcc manual, such as "-static", "--static-pie", "-fno-pic", "-fpic". I guess that:
    • "-static" will generate a no-pic executable.
    • "--static-pie" will generate a PIC executable which has some unknown symbols to be resolved in runtime.
    • "-fpic" is the default manner of gcc when genrating a shared library.
    • "-fno-pic" is commonly used in some special cases such as making an operating system.

Are these guesses correct?


Solution

    • fpic

    Generate position-independent code (PIC) suitable for use in a shared library. Such code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC; it is part of the operating system).

    • fpie

    These options are similar to -fpic, but the generated position-independent code can be only linked into executables. Usually these options are used to compile code that will be linked using the -pie GCC option.

    From gcc.gnu.org, Options for Code Generation Conventions

    • static

    On systems that support dynamic linking, this overrides -pie and prevents linking with the shared libraries. On other systems, this option has no effect.

    • static-pie

    Produce a static position independent executable on targets that support it. A static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker.

    From gcc.gnu.org, Options for Linking

    Imagine a day, where you can write a comment without account. (cringe)