A library is a bundle of ready-made functions that many programs can use without copying the source code. You already use one every day: printf lives in the C standard library. In this lesson you will build your own small library twice, once as a static library and once as a shared one, and see exactly how the two differ.
In this lesson you will learn
- Why programmers package code into libraries
- The difference between static (
.a) and shared (.so) libraries - How to write the header and source files for a library
- The exact
gccandarcommands to build and link both kinds - How to fix the linker and loader errors you will meet
Why Package Code as a Library?
Suppose three of your programs need the same area calculations. You could paste the functions into each program, but then every bug fix has to be made three times. A library solves this:
- Write once, reuse everywhere. Programs link to the library instead of carrying their own copy of the code.
- Hide the details. Users see only the header file. The private parts stay inside the library.
- Build faster. The library is compiled once. Programs that use it only need linking.
- Share safely. You can give someone a compiled library and a header without giving away your source code.
Static vs Shared Libraries
| Static library | Shared library | |
|---|---|---|
| File name on Linux | libname.a | libname.so |
| When the code joins your program | At link time: it is copied into the executable | At run time: the program loads it when it starts |
| Executable size | Larger | Smaller |
| Needs the library file at run time? | No | Yes |
| Fixing a bug in the library | Rebuild every program that uses it | Replace the .so file; programs pick up the fix next time they start |
| Windows equivalent | .lib | .dll |
Static libraries are simple and self-contained, which suits small tools and embedded systems. Shared libraries save disk space and memory when many programs use the same code, which is why most system libraries on Linux are shared.
Building and Linking Both Kinds Step by Step
Step 1: Write the Header
The header is the library’s public face. It declares what users may call, and nothing more.
/* geom.h - public interface of a tiny geometry library */
#ifndef GEOM_H
#define GEOM_H
double circle_area(double radius);
double rect_area(double width, double height);
int geom_calls(void); /* how many area functions have run */
#endif
Step 2: Write the Source File
/* geom.c - the library's implementation */
#include "geom.h"
static int calls = 0; /* private to the library */
double circle_area(double radius) {
calls++;
return 3.14159265358979 * radius * radius;
}
double rect_area(double width, double height) {
calls++;
return width * height;
}
int geom_calls(void) {
return calls;
}
The counter calls is static, so programs using the library cannot touch it directly. They can only read it through geom_calls(). (See internal and external linkage for why this works.)
Step 3: Write a Program That Uses It
/* main.c - a program that uses the library */
#include <stdio.h>
#include "geom.h"
int main(void) {
printf("circle r=2 : %.2f\n", circle_area(2.0));
printf("rectangle 3x4: %.2f\n", rect_area(3.0, 4.0));
printf("library calls: %d\n", geom_calls());
return 0;
}
Step 4: Build and Run Both Versions
# Static library
gcc -c -Wall geom.c -o geom.o # compile to an object file
ar rcs libgeom.a geom.o # pack it into an archive
gcc main.c -L. -lgeom -o app_static # link: -L = where, -l = which library
./app_static
# Shared library
gcc -c -fPIC -Wall geom.c -o geom_pic.o
gcc -shared geom_pic.o -o libgeom.so
gcc main.c -L. -lgeom -o app_shared
LD_LIBRARY_PATH=. ./app_shared # tell the loader where to find libgeom.so
ar t libgeom.a # list what is inside the archive
Output
--- static build ---
circle r=2 : 12.57
rectangle 3x4: 12.00
library calls: 2
--- shared build ---
circle r=2 : 12.57
rectangle 3x4: 12.00
library calls: 2
--- inside libgeom.a ---
geom.o
Both programs print the same results. What each command does:
-ccompiles without linking, producing an object file (.o).ar rcscreates an archive: replace or add files, create it if needed, and write an index (s) so the linker can search it quickly.-fPICmakes position-independent code, which can be loaded at any memory address. Shared libraries need it.-L.adds the current folder to the library search path.-lgeommeans “findlibgeom.aorlibgeom.so“. Leave out thelibprefix and the extension.
When both files exist, GCC prefers the shared one. Add -static to force static linking.
Linker and Path Errors
| Error | Cause | Fix |
|---|---|---|
undefined reference to 'circle_area' | The library was not linked, or it came before the file that uses it | Put -lgeom after main.c on the command line |
cannot find -lgeom | The linker does not know which folder holds the library | Add -L/path/to/folder |
error while loading shared libraries: libgeom.so | The program built fine, but the loader cannot find the .so at run time | Set LD_LIBRARY_PATH, install the library in a system folder and run ldconfig, or link with -Wl,-rpath,/path |
relocation ... recompile with -fPIC | Object files for a shared library were compiled without -fPIC | Recompile them with -fPIC |
multiple definition of ... | A function or variable is defined in the header, so every file that includes it gets a copy | Keep only declarations in headers |
Order matters because the linker reads left to right. It only pulls a function out of an archive if an earlier file has already asked for it. That is why gcc -lgeom main.c fails while gcc main.c -lgeom works.
Library Building Checklist
- Put only declarations, types and constants in the header, wrapped in an include guard.
- Make helper functions and internal variables
static. - Include your own header in the library’s source file, so the compiler checks that declarations and definitions match.
- Compile with
-Wall -Wextra, and add-fPICfor shared libraries. - Name the file
libname.aorlibname.soand link with-lname. - Place
-loptions after the files that use them. - Ship the header together with the library file.
Practice Exercises
Exercise 1. Add a function double triangle_area(double base, double height) to the library. Which files must change?
Show answer
Declare it in geom.h, define it in geom.c, then rebuild the library. For the static version, every program that wants it must be relinked. For the shared version, rebuilding libgeom.so is enough for programs that do not call the new function.
Exercise 2. The command gcc -L. -lgeom main.c -o app fails with “undefined reference”. Why?
Show answer
The library is listed before main.c. When the linker reads -lgeom, nothing needs its functions yet, so it takes nothing. Move -lgeom to the end.
Exercise 3. You delete libgeom.so. Which of the two programs still runs?
Show answer
app_static still runs, because the library code was copied into it. app_shared fails at start-up because the loader cannot find the library.
Frequently Asked Questions
Is a header file a library?
No. The header only declares the functions. The compiled code lives in the .a or .so file. You need both: the header for compiling, the library file for linking.
How do I see which shared libraries a program uses?
Run ldd ./app_shared on Linux. It lists each shared library and where the loader found it.
Can a static library contain several object files?
Yes. List them all: ar rcs libtools.a a.o b.o c.o. The linker copies only the object files your program actually needs.
Which should I choose for a beginner project?
Start with a static library. It has fewer moving parts and no run-time path problems.
Summary
- A library packages reusable functions behind a header file.
- Static libraries (
.a) are copied into the program at link time; shared libraries (.so) are loaded at run time. - Build a static library with
gcc -candar rcs; build a shared one with-fPICand-shared. - Link with
-Lfor the folder and-lfor the name, placed after your source files. - “Cannot open shared object file” is a run-time path problem, not a build problem.
