Static Libraries Using a Makefile in C
A C static library is built by compiling each .c file into a .o object file, then archiving those objects into a libname.a file with ar rcs; a Makefile makes both stages repeatable. Programs that use the library compile against its headers and link against the archive. This guide builds a small reusable library, links it into an application, and covers dependency files, installed archives, and common linker errors.
What a Static Library Is
A static library is an archive of compiled object files. On most Unix-like systems, the convention is:
- Library file:
libmathlib.a - Linker name:
-lmathlib - Public header:
include/mathlib.h - Compiled members inside the archive:
add.o,sub.o, and similar files
The .a file is not C source code and is not created directly from .c files. Each source file must first become an object file. The ar archiver then collects those objects into the archive.
When the linker builds an executable, it extracts the object members that satisfy symbols needed by the program. The final executable does not need the .a file at runtime, unlike a program that depends on a shared .so library.
How to Build and Use a Static Library With Make
This example uses GNU Make and a GCC- or Clang-compatible C compiler on a Unix-like system.
Choose the target that matches what you need before building:
| Goal | Make Target | Result |
|---|---|---|
| Build the archive only | make build/lib/libmathlib.a |
A reusable static library |
| Build the library and demo program | make |
libmathlib.a and an executable |
| Remove generated files | make clean |
Object files, dependency files, library, and demo removed |
Step 1: Create the Header and Source Files
- Use the following project layout, with source files in the project root and the public header under include/: Save the build file as
Makefile, which is the default filename thatmakelooks for.
static-demo/
├── Makefile
├── add.c
├── app.c
├── sub.c
└── include/
└── mathlib.h
- Put the public function declarations in
include/mathlib.h.
#ifndef MATHLIB_H
#define MATHLIB_H
int add(int left, int right);
int subtract(int left, int right);
#endif
- Implement the functions in add.c and sub.c with these source definitions:
#include "mathlib.h"
int add(int left, int right)
{
return left + right;
}
#include "mathlib.h"
int subtract(int left, int right)
{
return left - right;
}
- Create app.c as a separate program that uses the library. The program below calls both library functions and prints their results:
#include <stdio.h>
#include "mathlib.h"
int main(void)
{
printf("%d\n", add(8, 3));
printf("%d\n", subtract(8, 3));
return 0;
}
The header is part of the library’s interface. Applications include it at compile time, while the linker uses the .a archive later.
Step 2: Write the Makefile
- Create a file named Makefile in the project root with the following rules; when entering them, begin every recipe command with a tab character. The indented command lines in Make recipes must begin with a tab character.
CC := cc
AR := ar
CFLAGS := -Wall -Wextra -std=c11 -Iinclude
LIB := build/lib/libmathlib.a
APP := build/bin/demo
LIB_SRCS := add.c sub.c
APP_SRCS := app.c
SRCS := $(LIB_SRCS) $(APP_SRCS)
LIB_OBJS := $(LIB_SRCS:.c=.o)
APP_OBJS := $(APP_SRCS:.c=.o)
OBJS := $(LIB_OBJS) $(APP_OBJS)
.PHONY: all clean
all: $(LIB) $(APP)
build/lib build/bin:
mkdir -p $@
$(LIB): $(LIB_OBJS) | build/lib
$(AR) rcs $@ $^
$(APP): $(APP_OBJS) $(LIB) | build/bin
$(CC) $(CFLAGS) -o $@ $(APP_OBJS) -Lbuild/lib -lmathlib
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
%.d: %.c
$(CC) $(CFLAGS) -MM $< >$@
ifneq ($(MAKECMDGOALS),clean)
include $(SRCS:.c=.d)
endif
clean:
rm -f $(OBJS) $(SRCS:.c=.d) $(LIB) $(APP)
rmdir build/lib build/bin build 2>/dev/null || true
- The archive rule below passes the archive target and its object prerequisites to ar:
$(AR) rcs $@ $^
$@ means the target being built, which is build/lib/libmathlib.a. $^ means all prerequisites, which are add.o and sub.o.
The ar rcs options create or update the archive and write its symbol index:
rreplaces or adds archive members.ccreates the archive if needed.screates or updates the archive index used by linkers.
Step 3: Generate Header Dependency Files
- The following pattern writes a .d file from each .c source:
%.d: %.c
$(CC) $(CFLAGS) -MM $< >$@
- During normal builds, include the generated .d filenames with:
include $(SRCS:.c=.d)
The compiler writes dependencies such as:
add.o: add.c include/mathlib.h
That means changing include/mathlib.h makes make rebuild add.o, sub.o, or app.o when they include that header. The -MM option records project headers while leaving out standard system headers.
The conditional around include prevents make clean from needlessly rebuilding dependency files before removing them.
Step 4: Build and Run the Program
- From the project directory, run the default build command:
make
Make compiles the source files, creates build/lib/libmathlib.a, links build/bin/demo, and leaves generated dependency files beside the source files.
- Run the built demo program:
./build/bin/demo
It should print:
11
5
The link command is:
$(CC) $(CFLAGS) -o $@ $(APP_OBJS) -Lbuild/lib -lmathlib
-Lbuild/lib gives the linker a directory to search. -lmathlib tells it to look for a library named libmathlib.a or libmathlib.so in that directory.
The command below is incorrect because it uses the archive pathname as the value for -L: This is incorrect:
cc app.o -Lbuild/lib/libmathlib.a -lmathlib
The correct name-based form is:
cc app.o -Lbuild/lib -lmathlib -o demo
Step 5: Verify Incremental Rebuilds
- To test whether a header change triggers the needed rebuilds, update its timestamp:
touch include/mathlib.h
- Run make again to perform the incremental build:
make
Make should rebuild the affected object files before recreating the archive and relinking the application.
To remove all generated build output when you are done, run:
make clean
Linking an Existing Static Library
If another project already provides libwidget.a, you need both its header path and its library path.
A typical Makefile link rule looks like this:
CFLAGS += -Ithird_party/widget/include
LDFLAGS += -Lthird_party/widget/lib
LDLIBS += -lwidget
app: app.o
$(CC) -o $@ app.o $(LDFLAGS) $(LDLIBS)
Use these variables for their conventional roles:
CFLAGS: compiler options, including warnings and language settingsLDFLAGS: linker search paths and linker optionsLDLIBS: libraries such as-lwidget,-lm, and-pthread
The order matters for static archives. Put the object files that need symbols first, then the libraries that define them:
cc app.o -Lthird_party/widget/lib -lwidget -o app
If libwidget.a calls functions from the math library, place the math library after it:
cc app.o -Lthird_party/widget/lib -lwidget -lm -o app
When a directory contains both libwidget.so and libwidget.a, a normal -lwidget link may choose the shared library. To link one specific archive without ambiguity, give its pathname directly:
cc app.o third_party/widget/lib/libwidget.a -o app
Installing or Combining Static Archives
Static archives can be installed with GNU Libtool and ranlib, while GNU ar MRI scripts can merge object files with an existing archive.
Install a Libtool Static Archive
If a project uses GNU Libtool, its documented static-library installation form is:
libtool --mode=install ./install-sh -c libhello.a \
/local/lib/libhello.a
Confirm the built archive name and chosen installation directory before using that command. After installation, create or refresh the archive index:
ranlib /local/lib/libhello.a
Combine One Archive With Another
Do not expect this to merge archive members correctly on most systems:
ar rcs libnew.a a.o b.o oldlib.a
That command adds oldlib.a as an archive member rather than reliably extracting and merging its object members.
If oldlib.a should be the base archive, copy it and add new object files:
cp oldlib.a libnew.a && ar rs libnew.a a.o b.o
For GNU ar, an MRI script can merge object files and another archive. This Make rule creates libnew.a from a.o, b.o, and the members of oldlib.a:
libnew.a: a.o b.o oldlib.a
printf '%s\n' \
'create $@' \
'addmod a.o' \
'addmod b.o' \
'addlib oldlib.a' \
'save' \
'end' | $(AR) -M
addlib oldlib.a is the MRI instruction that imports the existing archive’s members. Replace oldlib.a with the actual archive filename produced by its build.
Check the Archive and Fix Common Errors
Use this table when a library builds but the application does not link or run as expected.
| Symptom | Likely Cause | Fix |
|---|---|---|
cannot find -lmathlib |
-L points to a file or wrong directory |
Use -Lbuild/lib -lmathlib for build/lib/libmathlib.a |
undefined reference to add |
Library is missing, named incorrectly, or appears before objects that need it | Put app.o before -lmathlib and confirm the archive contains the required object |
| Header changes do not trigger rebuilding | No generated dependency files | Add the .d rule and include $(SRCS:.c=.d) |
| New code is absent from the executable | Object file was not listed as an archive prerequisite | Add the object to LIB_OBJS, then rebuild the archive |
| Symbols from another library are unresolved | The static library has external dependencies | Add dependent libraries after the archive that needs them |
List archive members with:
ar t build/lib/libmathlib.a
You should see:
add.o
sub.o
Inspect symbols with:
nm build/lib/libmathlib.a
Look for exported function names such as add and subtract. If an object file is missing, check that its .c file appears in LIB_SRCS, then run make again.
Frequently Asked Questions
What is a Makefile in C?
A Makefile is a build instruction file read by make. It defines targets, prerequisites, and commands so C source files, object files, libraries, and executables rebuild only when needed. The default filename is Makefile.
How do I create a Makefile for a C static library?
Create a file named Makefile, compile each .c file into a .o file, and create the archive with ar rcs libname.a object1.o object2.o. Add the object files as prerequisites of the .a target so make rebuilds the library when a source file changes.
What is the difference between a static and shared library?
A static library is usually a .a archive whose required object members are linked into the executable at build time. A shared library is usually a .so file loaded or resolved at runtime. Static linking can simplify deployment, while shared libraries can let multiple programs use one installed library file.
Why do -L and -l use different values?
-L takes a directory path, such as -Lbuild/lib. -l takes the logical library name without the lib prefix or .a suffix, such as -lmathlib for libmathlib.a.
Do I need to run ranlib after ar rcs?
Usually no: ar rcs already writes the archive symbol index through its s option. Run ranlib /local/lib/libhello.a after an installation workflow when that workflow requires the installed archive to be indexed. Start with the example Makefile, run make, and use ar t to confirm that your archive contains every object file you intended to publish.
