How to Create and Extract Archives Using the ar Command in Linux

Before the widespread adoption of tar for general file compression, Unix systems relied on the ar (archive) command to bundle multiple files together. While it is rarely used for general backups today, ar remains a critical tool for software developers, as it is the standard utility used to create, modify, and extract static libraries (.a files) used by C and C++ compilers during the linking phase.

Creating a New Archive (Static Library)

If you have compiled several C source files into object files (e.g., math.o, string.o, and network.o), you can bundle them into a single static library file (e.g., libutils.a) so they can be easily linked into other software projects.

To create the archive and add the files, use the -c (create) and -r (replace/insert) flags.

ar -cr libutils.a math.o string.o network.o

This command creates libutils.a and inserts the three object files into it. If the archive already exists, the -r flag ensures that the existing object files inside the archive are safely replaced with your newer, updated versions.

Viewing the Contents of an Archive

If you download a pre-compiled static library from a third-party vendor and you want to verify exactly which object files are packaged inside it without extracting them, you can use the -t (table of contents) flag.

ar -t libutils.a

This will simply print a vertical list of the filenames contained within the archive (e.g., math.o, string.o).

Extracting Files from an Archive

If you need to extract an object file from a static library so you can analyze it with tools like objdump or readelf, you can use the -x (extract) flag.

ar -x libutils.a math.o

This command pulls the math.o file out of the archive and saves a copy to your current working directory. The original math.o remains safely inside libutils.a. If you want to aggressively extract every single file contained within the archive simultaneously, simply omit the specific filename:

ar -x libutils.a

Deleting Files from an Archive

If you discover that the network.o module contains a critical security vulnerability, and you want to strip it out of the library before shipping it to production, you can delete it directly from the archive using the -d (delete) flag.

ar -d libutils.a network.o

This alters the libutils.a file in place, removing the specified object file.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.