Static Libraries
- /
- The Blog — Skills & Methods /
- Static Libraries
- Michael
- C , Headers , Shell , Programming
- October 22, 2025
Table of Contents
How to Create and Use a Static Library
What is a Static Library?
A static library is an archive (.a) that groups together multiple object files (.o).
The code from this archive is copied at link time.
What is Linking?
Linking is the step where the linker assembles object files (.o) and resolves references to library symbols in order to create the final executable.
We use specific options during the compilation command:
-L<archive_path> and -l<name>
Let’s imagine we have a file named libexample.a.
cc -Wall -Wextra -Werror file.c -L. -lexample
This command can be divided into 3 parts:
cc -Wall -Wextra -Werror file.c: Standard compile command with flags-L.: Adds the current directory to the list of directories where the linker will look for libraries. The “.” is important because it represents the current directory path.-lexample: This option adds the library to the list of libs to find and use (the prefix “lib” is implied;libexamplebecomeslexample).
By convention, all .a files should start with “lib”.
This allows the linker to find the library using the above command.
Here’s how to make it work without using the “lib” prefix:
# File example.a
cc -Wall -Wextra -Werror file.c -L. -l:example.a
However, the first approach remains clearer and more readable.
Creating a Static Library
To create a static library, you need your functions written in one or more .c files.
Then, compile the file(s) to obtain object files:
cc -Wall -Wextra -Werror -c file.c
This command will produce a .o file.
With this file, you will create the archive.
There are two ways to create a .a archive:
ar rc libexample.a file.o
ranlib libexample.a
ar rcs libexample.a file.o
Both methods are equivalent, but the first is more portable on systems where ar does not support the s option.
Explanations:
| Arguments | Definitions |
|---|---|
| AR | Archive |
| RCS | Options: r = Replace; c = Create; s = Write/Update |
| RANLIB | Writes the symbol index into the archive. Ensures compatibility where ar does not support -s. |
R = Adds or replaces .o files (replaces if they already exist).
C = Creates the archive if it doesn’t exist and suppresses the creation warning.
S = Writes or updates the symbol index table inside the archive so the linker can quickly find symbols.
Useful AR commands:
ar t libexample.a # t = List library contents
ar x libexample.a file.o # x = Extract a member from the library
ar d libexample.a file.o # d = Delete a member from the library
Sources:
Pierre Gradot
GeeksforGeeks
man ar
Sources