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

Creating archives with the `ar` tool

Creating archives with the ar tool

What you'll learn: How to bundle multiple object files into a single .a static library file using the ar command.

The Digital Binder

Imagine you are writing a massive book. Instead of carrying around hundreds of loose pages, you put them into a three-ring binder. In C programming, those "pages" are your .o (object) files—the compiled versions of your code. The "binder" is a static library, which on Linux and macOS ends in a .a extension (short for "archive").

The ar tool is the utility that creates these binders. It doesn't compile code; it simply organizes your existing object files into one convenient package.

Using the ar Command

To create a library, you first need object files. Let's say you have two utility files, math_utils.c and str_utils.c. You would compile them to object files first, then archive them.

# 1. Compile the source files into object files (.o)
gcc -c math_utils.c str_utils.c

# 2. Archive them into a library named libutils.a
ar rcs libutils.a math_utils.o str_utils.o

In the command ar rcs libutils.a ..., the flags mean:

  • r (replace): Add the files to the archive. If the library already exists, replace the old versions with the new ones.
  • c (create): Create the archive if it doesn't already exist.
  • s (index): Create an index for the symbols (functions and variables). This makes it much faster for the compiler to find what it needs later.

Why bundle them?

Once you have libutils.a, you no longer need to keep track of a dozen individual .o files. When you want to build your final program, you simply tell the compiler to look at that one library file.

It also makes sharing code easier. If you want a teammate to use your math functions, you can just give them the libutils.a file and the corresponding .h header files. They don't need to see your source code or manage your individual object files; they just "plug in" the archive.

Key takeaway

The ar tool creates static libraries by bundling .o object files into a single .a archive for easier distribution and linking.