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

What is a static library `.a`

What is a static library .a

What you'll learn: How to bundle multiple object files into a single archive file that gets baked directly into your final program.

The "Toolbox" Analogy

Imagine you are building a wooden shed. You have two choices for your tools: you can carry every individual screwdriver, hammer, and saw separately in your pockets, or you can put them all into one sturdy toolbox.

In C programming, a static library (ending in .a for "archive" on Linux/macOS or .lib on Windows) is that toolbox. It is simply a collection of multiple object files (.o) bundled together into a single file for convenience.

How it works

When you write code, you often split functions into different files (e.g., math_utils.c, string_utils.c). Normally, you would compile these into object files and then link them all manually.

With a static library, you use a tool called an archiver (ar) to glue those .o files together. When it comes time to build your final application, the linker looks inside this archive, finds the functions you actually used, and copies their binary code directly into your executable file.

/* math_lib.c - Part of our library */
int add(int a, int b) {
    return a + b;
}

/* main.c - Our application */
#include <stdio.h>
#include "my_library.h"

int main() {
    // When we compile, the code for 'add' is 
    // literally copied from the .a file into our app.
    printf("Sum: %d\n", add(5, 5));
    return 0;
}

Why use them?

The "static" part of the name means the connection happens at compile-time. Because the library code is copied into your final program:

  1. Portability: You can send your finished .exe to a friend, and it will run even if they don't have the library on their computer. Everything it needs is inside.
  2. Speed: The computer doesn't have to look for external files when the program starts; the code is already there in memory.
  3. Organization: Instead of managing 50 different .o files, you only have to manage one .a file.

The trade-off is file size. If you have ten different programs all using the same static library, each program will have its own private copy of that library's code, wasting a bit of disk space.

Key takeaway

A static library is a permanent "copy-paste" of pre-compiled code into your program, ensuring your app is self-contained and ready to run.