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

What is a shared library `.so` / `.dll`

What is a shared library .so / .dll

What you'll learn: Understand how shared libraries save space and allow multiple programs to use the same code simultaneously.

Unlike a static library, which gets physically shoved inside your program's executable file, a shared library stays separate. On Windows, these are called Dynamic Link Libraries (.dll), and on Linux/macOS, they are Shared Objects (.so).

The "Public Library" Analogy

Imagine you are building a house. Using a static library is like buying your own personal cement mixer and locking it in your garage. It’s always there, but it takes up a lot of space, and your neighbor has to buy their own mixer too.

Using a shared library is like using a public tool-sharing program. The cement mixer stays at a central depot. When you need to pour a driveway, you call the depot. You don't own the mixer; you just "link" to it while your project is running. If ten people are building houses, they all use that same single mixer from the depot instead of ten people storing ten bulky machines.

How it works in C

When you compile a program to use a shared library, the compiler doesn't copy the library's code into your program. Instead, it leaves a "placeholder" or a note that says, "When this program starts, go find the code for calculate_physics() in physics_lib.so."

#include <stdio.h>
#include "physics_engine.h" // The header for our shared library

int main() {
    // This function isn't in our compiled file. 
    // The computer loads it from a .so or .dll file only when the program runs.
    double force = calculate_physics(10.5); 
    
    printf("Result: %f\n", force);
    return 0;
}

Why use them?

  1. Memory Efficiency: If five different programs all use the same shared library for graphics, the computer only loads that library into RAM once.
  2. Smaller File Sizes: Your program's .exe stays tiny because it doesn't contain the library code.
  3. Easy Updates: If you find a bug in the library, you only have to replace the one .dll or .so file. Every program that uses it will automatically start using the "fixed" version the next time they launch, without needing to be recompiled.

Key takeaway

Shared libraries are external files loaded at runtime, allowing multiple programs to share one copy of code to save disk space and memory.