Lesson 27 of 50
cHeader Files & Multiple Translation Units
11 mins
Course progress54%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 27 of 50
c11 mins
Keep these ideas in mind as you work through the lesson.
A translation unit is a source file after preprocessing. Splitting a project into multiple .c files improves modularity.
Typical layout:
project/
├─ src/
│ ├─ main.c // contains main()
│ └─ utils.c // implementation of utility functions
├─ include/
│ └─ utils.h // declarations for utils.c
├─ Makefile
└─ README.md
utils.h provides function prototypes and type definitions. utils.c includes the header and defines the functions. The compiler compiles each .c file separately, then the linker combines the object files.
gccgcc -Iinclude -c src/utils.c # produces utils.o
gcc -Iinclude -c src/main.c # produces main.o
gcc -o myprogram main.o utils.o
CC=gcc
CFLAGS=-Wall -Wextra -Iinclude
OBJ=main.o utils.o
myprogram: $(OBJ)
$(CC) -o $@ $^
%.o: src/%.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJ) myprogram