Make Automatic Variables Reference
Master Make automatic variables: $@, $<, $^, $*, $?, $|, and their directory/file variants. Practical examples for each variable in common build rules.
Detailed Explanation
Automatic Variables in Make
Automatic variables are set by Make for each rule and provide information about the target and prerequisites. They eliminate hardcoded file names in recipes.
The Core Variables
| Variable | Meaning | Example |
|---|---|---|
$@ |
Target file name | In main.o: main.c, $@ = main.o |
$< |
First prerequisite | In main.o: main.c utils.h, $< = main.c |
$^ |
All prerequisites | In main: a.o b.o, $^ = a.o b.o |
$* |
Pattern stem | In %.o: %.c matching src/main.o, $* = src/main |
$? |
Prerequisites newer than target | Only the changed files |
| `$ | ` | Order-only prerequisites |
Practical Examples
Compilation rule:
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
$@ is the .o file being built, $< is the .c source file.
Linking rule:
$(TARGET): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
$@ is the final binary, $^ is all object files.
Archiving:
libutils.a: $(LIB_OBJS)
ar rcs $@ $?
$? includes only object files newer than the archive, avoiding unnecessary re-archiving.
Directory and File Variants
Each variable has D (directory) and F (file) variants:
$(@D)— directory part of target (srcfromsrc/main.o)$(@F)— file part of target (main.ofromsrc/main.o)$(<D),$(<F)— same for first prerequisite
%.o: %.c
@mkdir -p $(@D)
$(CC) $(CFLAGS) -c -o $@ $<
$(@D) creates the output directory before compilation, supporting out-of-tree builds.
Order-Only Prerequisites
$(BIN_DIR)/app: src/main.c | $(BIN_DIR)
$(CC) -o $@ $<
$(BIN_DIR):
mkdir -p $@
The | separator marks $(BIN_DIR) as order-only — it must exist but its timestamp is not checked.
Use Case
Writing pattern rules for a C/C++ project build system where you need to understand and use automatic variables correctly to avoid hardcoding file paths in Makefile recipes.