Skip to content

Make Cheatsheet

Build automation tool that executes commands based on file dependencies.

01

Getting Started

Basic Makefile

Targets with tab-indented commands.

make
build:
	gcc -o main main.c

clean:
	rm -f main

run: build
	./main

Variables

Variables with $() expansion.

make
CC = gcc
CFLAGS = -Wall -O2

build:
	$(CC) $(CFLAGS) -o main main.c

Run

Run targets with make command.

make
# make build
# make clean
# make  # runs first target
02

Features

Dependencies

Targets depend on files; rebuilt when files change.

make
main.o: main.c header.h
	gcc -c main.c

main: main.o
	gcc -o main main.o

Pattern Rules

Pattern rules for generic build steps.

make
%.o: %.c
	gcc -c $< -o $@

# $< = first dependency
# $@ = target name

Functions

Functions: wildcard, patsubst, etc.

make
SRC = $(wildcard src/*.c)
OBJ = $(patsubst src/%.c,build/%.o,$(SRC))

build: $(OBJ)

Phony

Phony targets are not files.

make
.PHONY: clean all

all: build test

clean:
	rm -rf build/

Was this helpful?