Building with gcc, make & libraries
Compile multi-file projects with warnings on and a Makefile, and link static or shared libraries.
By Invicly Tech, , in Linux System Programming. About 10 minutes to read.
In short
gcc turns C source into an executable in four stages: preprocessing, compiling, assembling and linking. make rebuilds only what changed, based on file timestamps and dependency rules. Knowing how linking works explains errors like undefined reference and why shared libraries must be found at run time.
Explained simply
Your C source is just text. To run it, gcc turns it into machine code in several steps, and the last step, linking, glues your code together with code from libraries like libc. One command, gcc main.c -o app, hides all of that, but the steps are still there.
Big projects have many .c files. Recompiling everything after every small edit would be slow. make solves this: you describe which files depend on which, and make only rebuilds the parts whose inputs changed since the last build.
Libraries are bundles of ready-made code. A static library (.a) is copied into your program when it is linked. A shared library (.so) stays a separate file that is loaded when the program starts, so many programs share one copy in memory.
Turn on warnings from day one. Flags like -Wall -Wextra make gcc point out suspicious code, and most warnings are real bugs waiting to happen.
Press Play on a diagram to walk through it one step at a time.
- 1Preprocess
Expand #include and macros (gcc -E).
- 2Compile
Translate C to assembly (gcc -S).
- 3Assemble
Turn assembly into an object file (gcc -c).
- 4Link
Join objects and libraries into an ELF executable.
- 5Load
The dynamic loader maps shared libraries at run time.
- main.o (up to date)
- main.c unchanged
- util.h unchanged
- util.o (rebuilt)
- util.c changed
- util.h unchanged
- libc.so
- Linked dynamically, not rebuilt
In depth
Headers versus source files
A header (.h) holds declarations: "a function called parse exists and takes these arguments". A source file (.c) holds the definition: the actual body of parse. Every .c that calls parse includes the header so the compiler can check the call, but only one .c defines it.
The compiler works on one .c file at a time and turns it into an object file (.o). Calls to functions defined elsewhere are left as named holes. The linker then reads all the .o files and fills the holes. If a definition is missing you get "undefined reference"; if two files define the same function you get "multiple definition".
Include guards (#ifndef X_H / #define X_H / #endif) stop a header from being pasted twice into one file.
- Declarations in .h, definitions in .c
- One .c becomes one .o
- Undefined reference = linker could not find a definition
- 1util.h
Declares parse
- 2main.c
Includes util.h and calls parse
- 3main.o
parse left as a hole (nm shows U)
- 4util.o
parse defined here (nm shows T)
- 5Linker
Fills the hole, writes app
How make decides what to rebuild
A Makefile is a list of rules. Each rule says: this target depends on these prerequisites, and here is the recipe to build it. When you run make, it compares file modification times. If a target is missing or older than any of its prerequisites, make runs the recipe.
So if you edit util.c, make rebuilds util.o and then relinks app, but leaves main.o alone. Forgetting to list a header as a prerequisite is a classic trap: you change a struct in util.h, make thinks nothing changed, and you get strange crashes from stale objects. Adding -MMD -MP to CFLAGS makes gcc write dependency files that make can include automatically.
- Target is rebuilt if older than a prerequisite
- Mark clean and all as .PHONY
- -MMD -MP generates header dependencies
- make -j8 builds in parallel
Static and shared libraries
To build a static library, compile objects and bundle them with ar rcs libutil.a util.o. Linking with -L. -lutil copies only the needed objects into your binary. The result has no run-time dependency, but every program carries its own copy.
To build a shared library, compile with -fPIC (position-independent code) and link with gcc -shared -o libutil.so util.o. Your program then records that it needs libutil.so. At start-up the dynamic loader, ld.so, searches standard directories and LD_LIBRARY_PATH to find it. If it cannot, the program fails with "cannot open shared object file". Fixing a bug in a shared library fixes every program that uses it, without relinking.
- ar rcs libutil.a util.o
- Needed objects copied into the binary
- No run-time dependency
- Every program carries its own copy
- gcc -shared, objects built with -fPIC
- Binary only records the library name
- ld.so finds it at start-up
- One copy on disk for all programs
Inspecting what you built
A few small tools answer most build questions. file app tells you it is a 64-bit ELF executable and whether it is stripped. nm app lists symbols: T means a function defined here, U means undefined and expected from a library. ldd app lists the shared libraries the loader will pull in and where it found them. objdump -d disassembles machine code if you are curious what the compiler produced.
When a link fails, nm on each .o or .a usually shows which file was supposed to define the missing symbol.
- file: format and architecture
- nm: defined (T) and undefined (U) symbols
- ldd: shared library dependencies
- objdump -d: disassembly
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Follow preprocess, compile, assemble, link stages~50m
- 2Enable -Wall -Wextra and fix warnings~50m
- 3Write a Makefile with pattern rules~50m
- 4Build static and shared libraries~50m
- 5Inspect binaries with nm and ldd~50m
Key points
- Always compile with -Wall -Wextra and treat warnings as bugs.
- Use -g for debug info and -O2 for optimised release builds.
- Static libraries (.a) are copied into the binary; shared libraries (.so) are loaded at run time.
- Makefile recipe lines must start with a tab character.
Key terms
Tap a card to flip it. 0/6 known
Examples
CC = gcc
CFLAGS = -Wall -Wextra -g -O2
OBJS = main.o util.o
app: $(OBJS)
$(CC) $(CFLAGS) -o $@ $^
%.o: %.c util.h
$(CC) $(CFLAGS) -c $<
clean:
rm -f app $(OBJS)A minimal Makefile: $@ is the target, $^ all prerequisites, $< the first one.
Splitting a program into two files
We move a helper into its own file. util.h declares the function, util.c defines it, and main.c includes the header and calls it. Each .c compiles separately to a .o, then gcc links them. The commands show the stages explicitly so you can see where each error type would appear.
# util.h: #ifndef UTIL_H / #define UTIL_H / int square(int x); / #endif
# util.c: #include "util.h" int square(int x) { return x * x; }
# main.c: #include <stdio.h> #include "util.h"
# int main(void) { printf("%d\n", square(7)); return 0; }
gcc -Wall -Wextra -c util.c # -> util.o
gcc -Wall -Wextra -c main.c # -> main.o
gcc -o app main.o util.o # link
./app # 49
nm main.o | grep square # U square (needed)
nm util.o | grep square # T square (defined)Turning the helper into a shared library
Now we build util.c as libutil.so and link main against it. The program runs only when the loader can find the library, so we point LD_LIBRARY_PATH at the current directory for this test. ldd confirms where it was found. In real installs the library goes to /usr/local/lib and you run ldconfig instead.
gcc -Wall -fPIC -c util.c
gcc -shared -o libutil.so util.o
gcc -o app main.c -L. -lutil
./app # error: libutil.so: cannot open shared object file
LD_LIBRARY_PATH=. ./app # 49
LD_LIBRARY_PATH=. ldd ./app | grep utilQuick reference
- gcc -Wall -Wextra -g -O0 for debugging, -O2 for release
- gcc -c file.c makes file.o without linking
- Put -lfoo after the objects that use it on the link line
- ar rcs libx.a a.o b.o builds a static library
- gcc -shared -fPIC -o libx.so x.c builds a shared library
- make -j$(nproc) builds in parallel
- CFLAGS += -MMD -MP and -include $(OBJS:.o=.d) tracks headers
- nm, ldd, file and objdump -d inspect binaries
Common mistakes
- Putting -l libraries before the objects that need them on the link line.
- Using spaces instead of a tab in Makefile recipes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Compile hello.c with full warnings and debug info, then use file and ldd to describe the binary.
- Exercise 2medium
Write a Makefile for main.c and util.c (both include util.h) with targets app, clean and a .PHONY line. Editing util.h must rebuild both objects.
- Exercise 3hard
gcc -lm -o calc calc.o fails with undefined reference to sqrt on some systems, but gcc -o calc calc.o -lm works. Explain why.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need make if I only have one file?
- No, a single gcc command is fine. make starts paying off once you have several files or flags you do not want to retype.
- Should I link statically to avoid library problems?
- Static linking makes one self-contained binary, which is handy for small tools and containers. The cost is bigger files and needing to rebuild to pick up library security fixes, so most Linux software links dynamically.
- What is the difference between -O2 and -O3?
- -O3 enables more aggressive optimisations like heavier loop vectorisation. It is not always faster, so -O2 is the common default; measure before switching.