Course contentsShow
← C
Lesson 814 of 1,21911. The Preprocessor and BuildFree lesson

Position Independent Code `-fPIC`

Position Independent Code -fPIC

What you'll learn: Why shared libraries need to be generated as "relocatable" code so they can sit anywhere in your computer's memory.

The Problem with Fixed Addresses

Imagine you are writing a set of instructions for a friend to find a book in your house. If you say, "Walk exactly 10 feet from the front door and turn left," those instructions only work if your friend starts at the front door. If they are in the kitchen, your instructions are useless.

In standard programming, the compiler often generates code with "absolute addresses." It assumes the code will always start at a specific spot in the computer's memory. This is fine for a standalone program, but it creates a massive headache for shared libraries. Since a shared library (like libc) is used by many different programs simultaneously, it cannot guarantee it will always be loaded at the exact same memory address. If two libraries both demanded to live at memory address 0x1000, your system would crash.

The Solution: -fPIC

To solve this, we use the -fPIC flag (Position Independent Code) when compiling source files for a shared library.

When you use -fPIC, the compiler stops using fixed "house addresses" and starts using "relative directions." Instead of saying "Jump to address 500," the code says "Jump 20 bytes forward from where we are right now." This allows the operating system to jump the library to any available spot in memory, and the internal logic will still function perfectly.

How it looks in practice

You don't change your C code to use PIC; you change how you call the compiler. If you have a file called math_utils.c, you would compile it like this:

// math_utils.c - No special code required!
int add(int a, int b) {
    return a + b;
}

To prepare this for a shared library, you run: gcc -fPIC -c math_utils.c -o math_utils.o

This flag tells the compiler to generate a Global Offset Table (GOT). Think of this as a GPS for your code. Instead of hardcoding where a function lives, the code looks at the table to find the current location of the data it needs. This extra layer of redirection is what makes the code "position independent."

Key takeaway

The -fPIC flag ensures shared library code uses relative memory addresses rather than fixed ones, allowing multiple programs to share the same code regardless of where it is loaded in memory.