Build Systems, Libraries & Dependencies

targets, prerequisites, and recipes

These three words are the whole grammar of a Makefile rule. Think of building a sandwich: the sandwich is what you want (the target), the bread and filling are what it is made from (the prerequisites), and 'put the filling between the slices' is how you make it (the recipe). Every rule in a Makefile has this same shape.

Written out, a rule looks like 'target: prerequisite1 prerequisite2' on one line, followed by one or more recipe lines, each indented with a TAB, holding the shell commands. The target is usually the name of a file Make should create (like app or main.o), but can also be a label. The prerequisites are the files that target depends on; if any of them is newer than the target, Make considers the target out of date. The recipe is the exact commands Make runs to (re)build the target. This is called the dependency rule: a target depends on its prerequisites, and is rebuilt from them by its recipe.

Why it matters: by writing each piece's prerequisites honestly, you let Make build a complete picture of what depends on what, and rebuild in the correct order touching only what is needed. The classic mistake is forgetting a prerequisite, for example not listing a header file that a source file #includes; then Make will not rebuild when that header changes, and you get a stale, inconsistent program with no error message.

app: main.o util.o <- target : prerequisites gcc main.o util.o -o app <- recipe (TAB-indented) main.o is rebuilt only if main.c (or a header it needs) is newer than main.o.

The dependency rule in one picture: a target, the prerequisites it is built from, and the recipe that builds it.

Missing prerequisites are silent bugs: if a header a source depends on is not listed, Make will not rebuild on a header change, producing a stale binary. Real projects auto-generate header dependencies (e.g. gcc -MMD) to avoid this.

Also called
the dependency rulemake rule相依規則