Makefile by Example: Dependencies
Managing dependencies ensures that changing a header file triggers a recompile. This example shows how to track header dependencies.
Code
CC = gcc
DEPS = myheader.h
# The object files depend on the header file
# If myheader.h changes, main.o and func.o will be rebuilt
%.o: %.c $(DEPS)
$(CC) -c -o $@ $<
app: main.o func.o
$(CC) -o app main.o func.oExplanation
One of the main jobs of Make is to ensure that everything is up to date. If you modify a header file (.h) that is included by several C files, those C files need to be recompiled. If you don't declare this dependency, Make won't know it needs to rebuild the objects, and your executable might use old definitions.
In this example, we add $(DEPS) to the dependency list of the pattern rule. This means that every .o file generated by this rule depends not only on its corresponding .c file but also on myheader.h. If you touch myheader.h, Make sees that the dependencies are newer than the targets and recompiles everything.
For large projects, manually listing header dependencies is impractical. Advanced Makefiles often use compiler flags (like -M or -MMD in gcc) to automatically generate dependency files (.d) that list all the headers a source file includes, and then include those .d files in the Makefile.
Code Breakdown
%.o: %.c $(DEPS) declares that the object file depends on both the source file AND the headers in DEPS.
