Makefile Guide
Basic Structure
# target: prerequisites
# recipe (TAB-indented!)
.PHONY: all clean test
CC = gcc
CFLAGS = -Wall -O2
all: myapp
myapp: main.o utils.o
$(CC) $(CFLAGS) -o $@ $^
main.o: main.c main.h
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f *.o myapp
test: all
./myapp --test
Automatic Variables
| Variable | Meaning |
|---|---|
| $@ | Target name |
| $< | First prerequisite |
| $^ | All prerequisites |
| $? | Prerequisites newer than target |
| $* | Stem of pattern rule |
| $(@D) | Directory of target |
| $(@F) | File part of target |
Functions & Patterns
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c,obj/%.o,$(SRCS))
# Pattern rule
obj/%.o: src/%.c
@mkdir -p $(@D)
$(CC) $(CFLAGS) -c $< -o $@
# String functions
UPPER := $(shell echo $(NAME) | tr a-z A-Z)
FILTERED := $(filter %.c, $(FILES))
WITHOUT := $(filter-out test_%.c, $(SRCS))
# Conditional
ifeq ($(OS),Windows_NT)
EXE = .exe
else
EXE =
endif