fPIC option in GCC

fPIC option in GCC enables the address of shared libraries to be relative so that the executable is independent of the position of libraries. This enables one to share built library which has dependencies on other shared libraries.

fPIC stands for "force Position Independent Code". Note: Clang uses the same option -fPIC and the purpose is same.

The command is as follows:

gcc -L<path to .SO file> -Wall -o -fPIC code main.c -l<library name>

In case, you need not link to a shared library, the command is as follows:

gcc -Wall -o -fPIC code main.c

Table of contents:

  1. Basics of fPIC
  2. fPIC vs fpic
  3. fPIC vs fPIE

Let us get started with fPIC option in GCC.

Basics of fPIC

PIC stands for Position Independent Code.

PIC makes addresses in machine code relative to Global Offset Table (GOT). On some modern architecture, the size of GOT is restricted. Position Independent Code need special support in system hardware so these options can be used in specific systems only.

Example of Non-Position Independent Code (non-PIC):

209: JUMP_IF_EQUAL 239
239: NOP

Note we have a jump statement to address 239. This code may fail on a different system as the data on address 239 will be different. The idea is to make the jump statement relative.

Example of Position Independent Code (PIC):

230: NOP

Note the jump statement is to an address 30 steps after the current address.

fPIC vs fpic

With consideration of GOT, there are two flags:

  • -fPIC

  • -fpic

  • fPIC: emits Position Independent Code without considering GOT restrictions

  • fpic: emits Position Independent Code considering GOT restrictions. Therefore, -fpic should be preferred over -fPIC.

Note that PIC works only on certain machines and on OSX, one should use -fPIC and not -fpic.

When -fPIC is used, the following two macros are set:

  • __pic__ to 2
  • __PIC__ to 2

When -fpic is used, the following two macros are set:

  • __pic__ to 1
  • __PIC__ to 1

fPIC vs fPIE

Options like -fPIC and -fpic is used to make Position Independent Code considering and without considering GOT size respectively.

fPIE follow a similar line. PIE stands for Position Independent Executable.

So, code generated using fPIE can only be linked to another code as an executable and fPIE is without considering GOT size while fpie is with considering GOT size.

With this article at OpenGenus, you must have the complete idea of fPIC option in GCC.