GNU Make 4 cheatsheet

GNU Make 4: Variables and functions

8 common GNU Make 4 tasks.

Define variables

= is evaluated when used, := is evaluated once when defined, and ?= sets a default.

CC := gcc
CFLAGS ?= -O2 -Wall
SRC := $(wildcard src/*.c)

Automatic variables

$@ is the target, $< the first prerequisite, $^ all prerequisites.

app: a.o b.o
	$(CC) $^ -o $@

List files and change extensions

Find source files, then derive object file names from them.

SRC := $(wildcard src/*.c)
OBJ := $(SRC:src/%.c=build/%.o)

Run a command and capture its output

Store the output of a shell command in a variable.

VERSION := $(shell git describe --tags --always)

Use conditionals

Choose settings based on a variable.

ifeq ($(DEBUG),1)
CFLAGS += -g -O0
else
CFLAGS += -O2
endif

Include another makefile

Include shared rules. The leading minus ignores a missing file.

-include local.mk

Pass variables to commands

Export a variable to the environment of recipe commands.

export DATABASE_URL := postgres://localhost/app

Self-documenting help

Print each target's ## comment. Run it with make help.

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "%-15s %s\n", $$1, $$2}'

Was this page helpful?