GNU make automatic variables
When make runs a recipe it sets a handful of one-character automatic
variables that name the target, the prerequisites and the pattern stem.
Knowing them lets you write generic pattern rules instead of repeating file
names. This reference lists every automatic variable, its meaning, and the
D/F directory and file suffixes you can attach to each.
How it works
Automatic variables are set fresh for each rule that fires and are only valid inside that rule’s recipe (not in prerequisite lists, except via secondary expansion). The core ones:
%.o: %.c
$(CC) -c $< -o $@ # $< = first prereq (foo.c), $@ = target (foo.o)
program: main.o util.o
$(CC) $^ -o $@ # $^ = all prereqs deduped, $@ = program
For any automatic variable X, the forms $(XD) and $(XF) give the
directory part and the file part. So with target build/foo.o, $(@D) is
build and $(@F) is foo.o.
Tips and notes
$<is the first prerequisite — ideal as the single input to a compiler.$^deduplicates; reach for$+only when repeats matter (link order).$?is the subset of prerequisites that are newer than the target — handy for incremental archive updates.$*(the stem) is the safe way to derive sibling file names in pattern rules.- These are case-sensitive single characters;
$(MAKE),$(CURDIR)and friends are separate named special variables.