Variables and How Make Expands Them
How GNU Make variables really work: recursive versus simple expansion, command-line and environment overrides, the conventional CC/CFLAGS family, target-specific values, define and export.
By The Dark DebuggerUpdated 24 min read
Variables are where most Makefile bugs live, because Make expands them by rules that look
like a shell's but aren't. This article covers both kinds of variable, every assignment
operator, where a value can come from (the Makefile, the environment, the command line) and
which one wins, and the conventional names like CFLAGS and DESTDIR that other people and
tools expect your Makefile to honour. It continues the logstat project from
Your First Makefile; read that first if rules and
prerequisites are new to you.
Why variables
At the end of the last article, the Makefile said gcc -Wall -Wextra four times. To try
another compiler or add -O2, you'd edit four lines and hope you didn't miss one. And
nobody building your project could change the flags without editing your file.
There's also a new requirement. I've extended the report to show the mean and standard deviation of response sizes:
bytes: 6404 (mean 1067.3, stddev 1839.0)The standard deviation needs sqrt() from the C math library, which has to be linked
explicitly with -lm. So the link line needs a library too. Variables handle all of this.
Defining and using variables
A variable is a name, an assignment operator, and a value. You use it with $(NAME)
(${NAME} also works; $(...) is the common style):
CC := gcc
CFLAGS := -Wall -Wextra -O2
LDLIBS := -lm
OBJS := main.o parse.o report.o
.PHONY: all clean
all: logstat
logstat: $(OBJS)
$(CC) -o logstat $(OBJS) $(LDLIBS)
main.o: main.c parse.h report.h
$(CC) $(CFLAGS) -c main.c
parse.o: parse.c parse.h
$(CC) $(CFLAGS) -c parse.c
report.o: report.c report.h parse.h
$(CC) $(CFLAGS) -c report.c
clean:
rm -f logstat $(OBJS)make
./logstat access.loggcc -Wall -Wextra -O2 -c main.c
gcc -Wall -Wextra -O2 -c parse.c
gcc -Wall -Wextra -O2 -c report.c
gcc -o logstat main.o parse.o report.o -lm
logstat report
requests: 6
bytes: 6404 (mean 1067.3, stddev 1839.0)
2xx: 2
3xx: 1
4xx: 2
5xx: 1Make replaced each $(...) with its value before handing the line to the shell. That's what
you see echoed. Variables also work in targets and prerequisites (logstat: $(OBJS)), so the
object list lives in one place.
Values are plain text. There are no types and no quoting: CFLAGS := -Wall -Wextra -O2 stores
exactly those characters, and the spaces separate "words" when a function or prerequisite
list needs to split it. Names are case-sensitive. By convention, variables that users might
set are UPPERCASE.
Two flavors: = and :=
This is the single most important thing to understand about Make variables. There are two kinds, and they differ in when the right-hand side is expanded:
=makes a recursive variable. Make stores the text unexpanded and expands it every time the variable is used, using whatever the referenced variables hold at that moment.:=makes a simple variable. Make expands the right-hand side once, right now, and stores the result.
OPT = -O2
CFLAGS_RECURSIVE = -Wall $(OPT)
CFLAGS_SIMPLE := -Wall $(OPT)
OPT = -O0 -g
show:
@echo "recursive (=): $(CFLAGS_RECURSIVE)"
@echo "simple (:=): $(CFLAGS_SIMPLE)"make -f flavors.mkrecursive (=): -Wall -O0 -g
simple (:=): -Wall -O2CFLAGS_SIMPLE captured -O2 at the moment of assignment. CFLAGS_RECURSIVE stored the
text -Wall $(OPT) and looked up OPT when the recipe ran, after it had changed to
-O0 -g. (make -f reads a Makefile with a different name; I keep small experiments in
.mk files next to the real Makefile.)
Recursive variables have one hard limit: a recursive variable can't refer to itself, because expanding it would never end. This line, common in Makefiles translated from shell scripts, fails:
CFLAGS = -Wall
CFLAGS = $(CFLAGS) -O2selfref.mk:2: *** Recursive variable 'CFLAGS' references itself (eventually). Stop.Use += to append (below), or := if you really mean "the old value plus this".
Which should you use? My rule: default to :=. Its behaviour is what you'd expect from
any programming language, it's evaluated once (which matters when the value runs a command;
see $(shell ...) in Built-in Functions), and reading the
file top to bottom tells you the value. Reach for = when you deliberately want late
binding: a value that refers to something defined later, or to per-target values like the
ones later in this article.
Conditional assignment: ?=
?= assigns only if the variable isn't already defined. It's how a Makefile offers a default
that the environment or command line can replace:
PREFIX ?= /usr/local
CC ?= gcc
show:
@echo "PREFIX=[$(PREFIX)] CC=[$(CC)]"make -f cond.mk
PREFIX=/opt/logstat make -f cond.mk
PREFIX= make -f cond.mk
make -f cond.mk PREFIX=/srv/logstat CC=clangPREFIX=[/usr/local] CC=[cc]
PREFIX=[/opt/logstat] CC=[cc]
PREFIX=[] CC=[cc]
PREFIX=[/srv/logstat] CC=[clang]Line by line:
- Nothing set, so
PREFIXgot the default. ButCCiscc, notgcc. Make has built-in defaults for common variables, andCCis already defined asccbefore your Makefile is read. SoCC ?= gccnever does anything. On Linux,ccis the system C compiler (GCC here), so it's usually fine, but it surprises people. - An environment variable counts as "defined", so
?=left it alone. - An environment variable set to the empty string is also defined, so
?=didn't fire andPREFIXis empty. That's a real way to end up installing into/bin. - Command-line values beat everything in the file.
Appending: += and override
+= adds words to the end of a variable, with a space in between:
CFLAGS := -Wall -Wextra
CFLAGS += -O2
override CPPFLAGS += -D_GNU_SOURCE
show:
@echo "CFLAGS=[$(CFLAGS)] CPPFLAGS=[$(CPPFLAGS)]"make -f append.mk
make -f append.mk CFLAGS=-O0 CPPFLAGS=-DDEBUGCFLAGS=[-Wall -Wextra -O2] CPPFLAGS=[-D_GNU_SOURCE]
CFLAGS=[-O0] CPPFLAGS=[-DDEBUG -D_GNU_SOURCE]The second run shows the catch. A variable set on the command line replaces the Makefile's
value completely, += lines included, so -Wall -Wextra -O2 vanished. The override
directive makes a Makefile assignment apply even when the user set the variable on the
command line, so -D_GNU_SOURCE survived and was appended to the user's -DDEBUG. Use
override ... += for flags the code genuinely can't compile without, and leave everything
else overridable.
+= keeps the variable's flavor: appending to a := variable expands the new text
immediately, and appending to a = variable keeps it unexpanded.
Every assignment operator
| Operator | Name | Behaviour |
|---|---|---|
= | recursive | Store text; expand on every use |
:= | simple | Expand now; store the result |
::= | simple (POSIX spelling) | Same as :=; GNU Make 4.0+ |
?= | conditional | Assign (recursively) only if not already defined |
+= | append | Add a space and the new text; keeps the flavor |
!= | shell | Run the right-hand side as a shell command and store its output; GNU Make 4.0+ |
Where values come from, and who wins
A variable can be set in five places. When they conflict, this is the order, highest first:
| Source | Example | $(origin VAR) reports |
|---|---|---|
override in the Makefile | override CFLAGS += -std=c11 | override |
| Command line | make CFLAGS=-O3 | command line |
| The Makefile | CFLAGS := -O2 | file |
| The environment | CFLAGS=-O3 make | environment |
| Make's built-in defaults | CC is cc | default |
The surprising row is the environment: it loses to the Makefile. This Makefile prints each
variable's value and, using the origin function, where it came from:
CC := gcc
CFLAGS ?= -O2
show:
@echo "CC=$(CC) ($(origin CC)) CFLAGS=$(CFLAGS) ($(origin CFLAGS))"make -f precedence.mk
CC=clang CFLAGS=-O3 make -f precedence.mk
make -f precedence.mk CC=clang CFLAGS=-O3
CC=clang make -e -f precedence.mkCC=gcc (file) CFLAGS=-O2 (file)
CC=gcc (file) CFLAGS=-O3 (environment)
CC=clang (command line) CFLAGS=-O3 (command line)
CC=clang (environment override) CFLAGS=-O2 (file)In the second run, CC=clang in the environment was silently ignored, because the Makefile
assigns CC with :=. CFLAGS from the environment was used only because the Makefile used
?=. Command-line variables won both times. make -e flips the environment above the
Makefile for every variable, which is a blunt instrument I'd avoid.
The practical lesson for CI and for users: pass variables on the command line
(make CC=clang), not as environment variables (CC=clang make), unless you know the
Makefile uses ?= or leaves the variable alone.
The conventional variables
Make's built-in rules, and decades of habit, give a set of variable names fixed meanings. Use them and your Makefile behaves the way packagers, CI systems and other developers expect. You can see the built-in defaults by printing Make's database with no Makefile at all:
make -p -f /dev/null 2>/dev/null | grep -E '^(CC|CXX|CPP|AR|ARFLAGS|RM|LD|LINK.o|COMPILE.c) ='(-p prints the database; the 2>/dev/null hides the "No targets" complaint, since
/dev/null is an empty Makefile.)
ARFLAGS = rv
AR = ar
LINK.o = $(CC) $(LDFLAGS) $(TARGET_ARCH)
COMPILE.c = $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
CPP = $(CC) -E
RM = rm -f
LD = ld
CXX = g++
CC = ccCOMPILE.c and LINK.o are the commands Make's own built-in rules use, built from the
variables below. Pattern Rules shows those rules at work.
| Variable | Meaning | Typical value |
|---|---|---|
CC | C compiler | cc, gcc, clang |
CXX | C++ compiler | g++, clang++ |
CPPFLAGS | Preprocessor flags: include paths and macros | -Iinclude -DNDEBUG |
CFLAGS | C compiler flags: optimisation, debug info | -O2 -g |
CXXFLAGS | C++ compiler flags | -O2 -std=c++20 |
LDFLAGS | Linker flags: library search paths, linker options | -L/opt/lib -Wl,--as-needed |
LDLIBS | Libraries to link, after the objects | -lm -lpthread |
AR, ARFLAGS | Static library archiver and its flags | ar, rv |
PREFIX | Where the software will live once installed | /usr/local |
DESTDIR | Staging root prepended to every install path | empty, or pkgroot |
Here is logstat rewritten to follow the conventions:
# Override any of these on the command line, for example:
# make CC=clang CFLAGS='-O0 -g' PREFIX=/opt/logstat
CFLAGS ?= -O2
WARNINGS := -Wall -Wextra
LDLIBS := -lm
PREFIX ?= /usr/local
BINDIR := $(PREFIX)/bin
OBJS := main.o parse.o report.o
.PHONY: all debug install uninstall clean
all: logstat
debug: CFLAGS := -O0 -g
debug: CPPFLAGS += -DDEBUG
debug: logstat
logstat: $(OBJS)
$(CC) $(LDFLAGS) -o logstat $(OBJS) $(LDLIBS)
main.o: main.c parse.h report.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c main.c
parse.o: parse.c parse.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c parse.c
report.o: report.c report.h parse.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c report.c
install: logstat
install -d $(DESTDIR)$(BINDIR)
install -m 755 logstat $(DESTDIR)$(BINDIR)/logstat
uninstall:
rm -f $(DESTDIR)$(BINDIR)/logstat
clean:
rm -f logstat $(OBJS)The decisions behind it:
CCisn't set at all. The built-inccis right on Linux, and leaving it alone means bothmake CC=clangandCC=clang makework, since the environment beats a built-in default.CFLAGSbelongs to the user. It defaults to-O2with?=, so a distribution's build system can pass its own. The warnings the project always wants live in a separateWARNINGSvariable that overridingCFLAGSdoesn't wipe out.LDLIBSgoes after the objects on the link line. The order matters to the linker; Common mistakes shows what happens otherwise.
make
make clean
make CFLAGS='-O0 -g'cc -Wall -Wextra -O2 -c main.c
cc -Wall -Wextra -O2 -c parse.c
cc -Wall -Wextra -O2 -c report.c
cc -o logstat main.o parse.o report.o -lm
rm -f logstat main.o parse.o report.o
cc -Wall -Wextra -O0 -g -c main.c
cc -Wall -Wextra -O0 -g -c parse.c
cc -Wall -Wextra -O0 -g -c report.c
cc -o logstat main.o parse.o report.o -lmThe double space after cc is where the empty CPPFLAGS (and LDFLAGS) expanded to
nothing. And because CFLAGS uses ?=, the environment works too:
make clean
CFLAGS='-O1' makerm -f logstat main.o parse.o report.o
cc -Wall -Wextra -O1 -c main.c
cc -Wall -Wextra -O1 -c parse.c
cc -Wall -Wextra -O1 -c report.c
cc -o logstat main.o parse.o report.o -lmPREFIX and DESTDIR
PREFIX says where the program will live when it runs. DESTDIR says where to put the
files right now. They're separate because packaging tools build a package by installing into
a scratch directory and archiving it. Run without either, install targets the real system,
which needs root:
make installinstall -d /usr/local/bin
install -m 755 logstat /usr/local/bin/logstat
install: cannot create regular file '/usr/local/bin/logstat': Permission denied
make: *** [Makefile:33: install] Error 1With a staging directory, nothing outside the project is touched, and the layout inside
stage/ is exactly what would land on the target system:
make install DESTDIR=stage
make install PREFIX=/opt/logstat DESTDIR=stage
find stage -type f | sortinstall -d stage/usr/local/bin
install -m 755 logstat stage/usr/local/bin/logstat
install -d stage/opt/logstat/bin
install -m 755 logstat stage/opt/logstat/bin/logstat
stage/opt/logstat/bin/logstat
stage/usr/local/bin/logstatNote how DESTDIR is glued to the front of the path with no slash: $(DESTDIR)$(BINDIR).
BINDIR already starts with /. Support DESTDIR in every install rule you write. Package
builders assume it works and are quietly annoyed when it doesn't.
Target-specific and pattern-specific variables
A variable can be given a different value for one target and everything that target builds.
The debug lines in the Makefile above do that:
debug: CFLAGS := -O0 -g
debug: CPPFLAGS += -DDEBUG
debug: logstatWhile Make is building debug, and every prerequisite it builds on the way, CFLAGS is
-O0 -g and CPPFLAGS has -DDEBUG added. That inheritance is useful, and it has a trap.
Watch what happens if a normal build already exists:
make
make debugcc -Wall -Wextra -O2 -c main.c
cc -Wall -Wextra -O2 -c parse.c
cc -Wall -Wextra -O2 -c report.c
cc -o logstat main.o parse.o report.o -lm
make: Nothing to be done for 'debug'.The object files were up to date by timestamp, and Make doesn't track which flags built them.
So make debug produced nothing, and you're about to debug an optimised binary. Clean first
and the debug flags reach every compile:
make clean
make debugrm -f logstat main.o parse.o report.o
cc -DDEBUG -Wall -Wextra -O0 -g -c main.c
cc -DDEBUG -Wall -Wextra -O0 -g -c parse.c
cc -DDEBUG -Wall -Wextra -O0 -g -c report.c
cc -o logstat main.o parse.o report.o -lmThe real fix is to build debug and release into different directories so their objects can't mix. That needs pattern rules, which is the next article.
You can also attach a variable to a single file, or to every target matching a % pattern.
I appended these two lines to the Makefile:
parse.o: CFLAGS += -funroll-loops
%.o: WARNINGS += -Wconversionmakecc -Wall -Wextra -Wconversion -O2 -c main.c
cc -Wall -Wextra -Wconversion -O2 -funroll-loops -c parse.c
cc -Wall -Wextra -Wconversion -O2 -c report.c
report.c: In function ‘stats_add’:
report.c:10:37: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion]
10 | s->bytes_sq += (double)e->bytes * e->bytes;
| ^
[…]
cc -o logstat main.o parse.o report.o -lmOnly parse.o got the extra optimisation flag, and every .o got the stricter warning,
which immediately found three spots worth a look. The common real-world use for
pattern-specific variables is narrower, for example vendor/%.o: WARNINGS := to silence
warnings in third-party code you don't maintain.
Multi-line variables with define
define ... endef creates a variable whose value spans several lines. A common use is a help
message:
PREFIX ?= /usr/local
define HELP_TEXT
logstat build targets:
make build ./logstat
make debug build with -O0 -g and DEBUG defined
make install install to $(PREFIX)/bin (change with PREFIX=...)
make clean delete build output
endef
export HELP_TEXT
.PHONY: help
help:
@echo "$$HELP_TEXT"make -f help.mklogstat build targets:
make build ./logstat
make debug build with -O0 -g and DEBUG defined
make install install to /usr/local/bin (change with PREFIX=...)
make clean delete build outputdefine creates a recursive variable, so $(PREFIX) was expanded when the help was shown.
make -f help.mk PREFIX=/opt/logstat prints install to /opt/logstat/bin. The odd-looking
export plus $$HELP_TEXT is deliberate. Writing @echo "$(HELP_TEXT)" would paste the
newlines into the recipe, and Make would run each line as a separate command. Exporting the
variable puts it in the shell's environment, and $$ (next section) lets the shell expand it
as one string. define is also how you write reusable recipe snippets and templates for
$(eval ...), which we'll use in Built-in Functions.
$$: getting a dollar sign to the shell
Make expands $ in recipes before the shell sees them. So a shell variable like $f or a
command substitution $(wc ...) must be written with $$, which Make turns into a single
$:
.PHONY: sizes sizes-broken home home-broken
sizes:
@for f in *.c; do echo "$$f: $$(wc -l < $$f) lines"; done
sizes-broken:
@for f in *.c; do echo "$f: $(wc -l < $f) lines"; done
home:
@echo "home is $$HOME"
home-broken:
@echo "home is $HOME"make -f dollar.mk sizes
make -f dollar.mk sizes-brokenmain.c: 24 lines
parse.c: 9 lines
report.c: 25 lines
: lines
: lines
: linesIn the broken version, Make expanded $f as its own (empty) variable f, and
$(wc -l < $f) as a variable with a strange name, also empty. The shell received
echo ": lines" three times. No error, just wrong output. The HOME pair shows another
twist:
make -f dollar.mk home
make -f dollar.mk home-brokenhome is /home/sid
home is OMEWithout parentheses, $ takes exactly one character as the variable name. $HOME is the
Make variable H (empty) followed by the text OME. Rule of thumb: in a recipe, $(...)
is Make's, and $$ is the shell's.
export: passing variables to recipe commands
Make variables are not automatically environment variables for the commands in recipes. Only
variables that came from the environment in the first place, variables set on the command
line, and variables you export are passed down:
REGION := eu-west-1
export TZ := UTC
.PHONY: env-check
env-check:
@sh -c 'echo "REGION seen by the shell: $${REGION:-<unset>}"'
@echo "make itself expands REGION to: $(REGION)"
@date -d '2026-11-09 18:30:00 -0500' +'release time: %Y-%m-%d %H:%M %Z'make -f export.mkREGION seen by the shell: <unset>
make itself expands REGION to: eu-west-1
release time: 2026-11-09 23:30 UTCREGION existed only inside Make. TZ was exported, so date printed in UTC. That's a
cheap way to make timestamps in build output independent of whoever runs the build. (Run
make -f export.mk REGION=us-east-1 and the shell does see us-east-1, because command-line
variables are exported automatically.) Change the first line to export REGION := eu-west-1
and the shell sees the Makefile's value too:
REGION seen by the shell: eu-west-1
make itself expands REGION to: eu-west-1
release time: 2026-11-09 23:30 UTCExport what a script or tool in a recipe reads from its environment (AWS_REGION,
KUBECONFIG, GOFLAGS). A bare export line with no names exports every variable in the
Makefile to every command, which leaks values into tools that happen to read them; I'd avoid
it.
Where you'll use this
Two places where variables do most of the work.
Packaging. The CFLAGS ?=, PREFIX ?= and $(DESTDIR) pattern above is what lets a
distribution build your project without patching it. A package recipe effectively runs
make CFLAGS='...hardening flags...' PREFIX=/usr and then
make install PREFIX=/usr DESTDIR=<staging dir>, and archives the staging directory.
Container images. A task-runner Makefile that tags images from Git is one of the most common Makefiles in the wild:
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
REGISTRY ?= registry.example.com/tools
IMAGE := $(REGISTRY)/logstat:$(VERSION)
.PHONY: image push
image:
docker build --build-arg VERSION=$(VERSION) -t $(IMAGE) .
push: image
docker push $(IMAGE)VERSION uses := so git describe runs once, not every time the variable is mentioned.
REGISTRY uses ?= so CI can point it elsewhere. Docker isn't available in my test
environment, so I used make -n to print the commands without running them. The project
was tagged v1.2.0 in Git:
make -n push
make -n push REGISTRY=ghcr.io/acmedocker build --build-arg VERSION=v1.2.0 -t registry.example.com/tools/logstat:v1.2.0 .
docker push registry.example.com/tools/logstat:v1.2.0
docker build --build-arg VERSION=v1.2.0 -t ghcr.io/acme/logstat:v1.2.0 .
docker push ghcr.io/acme/logstat:v1.2.0With an uncommitted change in the working tree, git describe --dirty marks the version, so
an image built from unreviewed code can't be mistaken for the release:
docker build --build-arg VERSION=v1.2.0-dirty -t registry.example.com/tools/logstat:v1.2.0-dirty .Common mistakes
A comment at the end of a variable line
Make keeps the spaces between the value and a # comment:
OUT_DIR = build # where release artifacts go
.PHONY: package
package: logstat
mkdir -p $(OUT_DIR)/bin
cp logstat $(OUT_DIR)/bin/make -f trailing.mkmkdir -p build /bin
cp logstat build /bin/
cp: cannot create regular file '/bin/logstat': Permission denied
cp: -r not specified; omitting directory 'build'
make: *** [trailing.mk:6: package] Error 1OUT_DIR is build followed by three spaces, so $(OUT_DIR)/bin became two separate words,
build and /bin. The cp tried to copy into the system's /bin. A permission error
saved us here; as root, it would have succeeded. Put comments on their own line. For
inherited Makefiles, $(strip ...) trims the value; the last exercise does both.
Libraries in LDFLAGS instead of LDLIBS
Putting -lm in LDFLAGS looks harmless, since it's a linker flag after all:
grep -n 'lm\|-o logstat' Makefile
make5:LDFLAGS := -lm
20: $(CC) $(LDFLAGS) -o logstat $(OBJS)
cc -Wall -Wextra -O2 -c main.c
cc -Wall -Wextra -O2 -c parse.c
cc -Wall -Wextra -O2 -c report.c
cc -lm -o logstat main.o parse.o report.o
[…]
report.c:(.text+0x1c4): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
make: *** [Makefile:20: logstat] Error 1The linker reads its arguments left to right. When it saw -lm, nothing yet needed sqrt,
so (with Ubuntu's default --as-needed linking) the library was dropped before report.o
asked for it. Libraries go in LDLIBS, after the objects. LDFLAGS is for options like
-L search paths. I trimmed one line of linker output above that shows the linker's path.
Expecting CC=clang make to work
As the precedence table shows, an environment variable loses to any assignment in the
Makefile. If a Makefile says CC := gcc, then CC=clang make silently builds with GCC.
make CC=clang always works. When you write Makefiles, use ?= or no assignment at all for
anything users are likely to set from the environment.
$VAR in a recipe
$HOME is $(H)OME, and $f is Make's variable f. Shell variables in recipes need $$.
It never produces an error, only wrong output, so check the echoed command when a loop or
$(...) substitution in a recipe "does nothing".
Summary
=stores text and expands it on every use (late binding).:=expands once, at assignment. Default to:=; a recursive variable can't refer to itself.?=assigns only if the variable is undefined. Empty counts as defined, and built-ins likeCCare already defined, soCC ?= gccdoes nothing.- Precedence, highest first:
overridein the Makefile, command line, Makefile, environment, built-in default. Pass settings asmake VAR=value. - Conventional names:
CC,CPPFLAGS(-I,-D),CFLAGS(-O,-g),LDFLAGS(-L),LDLIBS(-l, after the objects),PREFIX(runtime location),DESTDIR(staging root in front of every install path). target: VAR = valueapplies to that target and everything it builds. Make doesn't track flags, so existing objects aren't rebuilt when a target-specific flag changes.define/endefholds multi-line values.exportpasses a variable to recipe commands.- In recipes,
$(...)is Make's and$$is the shell's.$HOMEmeans$(H)followed byOME. - Never put a comment after a value on the same line: the spaces before
#become part of the value.
Exercises
Without running it, predict what this prints. Then run it and explain any difference.
NAME = logstat
GREETING_A = building $(NAME)
GREETING_B := building $(NAME)
NAME = logstat-ng
show:
@echo "A: $(GREETING_A)"
@echo "B: $(GREETING_B)"Show Solution
make -f ex1.mkA: building logstat-ng
B: building logstatGREETING_A is recursive: it stores building $(NAME) and looks NAME up when the recipe
runs, after NAME has changed. GREETING_B is simple: it captured logstat at the moment
of assignment. The order of lines in the file matters for := and doesn't for =.
Using the conventional logstat Makefile from this article, and without editing it or
installing anything, show the exact commands a clean build would run with clang and -O3.
Show Solution
make -n CC=clang CFLAGS=-O3clang -Wall -Wextra -O3 -c main.c
clang -Wall -Wextra -O3 -c parse.c
clang -Wall -Wextra -O3 -c report.c
clang -o logstat main.o parse.o report.o -lmCommand-line variables override the Makefile, and -n prints without running, so clang
doesn't even need to be installed. The warnings survived because they live in WARNINGS,
not in the CFLAGS we replaced.
Add a dist target that creates dist/logstat-<version>.tar.gz containing the program and
README.md. The version should default to 1.2.0 and be overridable from the command line.
Build one tarball with the default and one for 1.3.0-rc1.
Show Solution
VERSION ?= 1.2.0
DISTNAME := logstat-$(VERSION)
.PHONY: dist
dist: logstat
rm -rf dist
mkdir -p dist/$(DISTNAME)
cp logstat README.md dist/$(DISTNAME)/
tar -C dist -czf dist/$(DISTNAME).tar.gz $(DISTNAME)
@echo "created dist/$(DISTNAME).tar.gz"make dist
make dist VERSION=1.3.0-rc1 | tail -n 1
ls distcc -Wall -Wextra -O2 -c main.c
cc -Wall -Wextra -O2 -c parse.c
cc -Wall -Wextra -O2 -c report.c
cc -o logstat main.o parse.o report.o -lm
rm -rf dist
mkdir -p dist/logstat-1.2.0
cp logstat README.md dist/logstat-1.2.0/
tar -C dist -czf dist/logstat-1.2.0.tar.gz logstat-1.2.0
created dist/logstat-1.2.0.tar.gz
created dist/logstat-1.3.0-rc1.tar.gz
logstat-1.3.0-rc1
logstat-1.3.0-rc1.tar.gzDISTNAME can safely use := because the command-line value of VERSION is already in
place before the Makefile is read. The rm -rf dist at the start is why only the second
tarball is left.
Extend install and uninstall so they also handle README.md, installed to
$(PREFIX)/share/doc/logstat/README.md with mode 644. Test it the way a package builder
would: PREFIX=/usr, staged into pkgroot, with no root access needed.
Show Solution
PREFIX ?= /usr/local
BINDIR := $(PREFIX)/bin
DOCDIR := $(PREFIX)/share/doc/logstat
.PHONY: install uninstall
install: logstat
install -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(DOCDIR)
install -m 755 logstat $(DESTDIR)$(BINDIR)/logstat
install -m 644 README.md $(DESTDIR)$(DOCDIR)/README.md
uninstall:
rm -f $(DESTDIR)$(BINDIR)/logstat
rm -rf $(DESTDIR)$(DOCDIR)make install PREFIX=/usr DESTDIR=pkgroot
find pkgroot -type f | sort
make uninstall PREFIX=/usr DESTDIR=pkgrootinstall -d pkgroot/usr/bin pkgroot/usr/share/doc/logstat
install -m 755 logstat pkgroot/usr/bin/logstat
install -m 644 README.md pkgroot/usr/share/doc/logstat/README.md
pkgroot/usr/bin/logstat
pkgroot/usr/share/doc/logstat/README.md
rm -f pkgroot/usr/bin/logstat
rm -rf pkgroot/usr/share/doc/logstatDefining DOCDIR once keeps install and uninstall from disagreeing about the path. The
uninstall removes only the project's own doc directory, never $(PREFIX)/share/doc itself.
Take the broken package target from Common mistakes and fix it twice: once by changing
where the comment lives, and once without touching the original line, as you might with a
Makefile you've inherited. Confirm both put logstat in build/bin.
Hint
$(strip ...) removes leading and trailing whitespace and collapses internal runs of spaces.
A simple variable can be reassigned from its own old value.
Show Solution
Fix 1, move the comment:
# where release artifacts go
OUT_DIR = buildFix 2, leave the line alone and clean the value afterwards:
OUT_DIR = build # where release artifacts go
OUT_DIR := $(strip $(OUT_DIR))Both give the same, correct commands:
make package
ls build/binmkdir -p build/bin
cp logstat build/bin/
logstatFix 2 works because := expands the right-hand side immediately, while OUT_DIR still holds
its old recursive value, and stores the stripped result. That's a self-reference = can't
do. Prefer fix 1 in code you own.
Tested with: GNU Make 4.3, GCC 13.3 and Git 2.43 on Ubuntu 24.04 (WSL2), November 2026.
Every Makefile and output above was run as shown. The trims are three repeated -Wconversion
warnings and one linker line that contains the toolchain's install path. Docker isn't
installed in the test environment, so the image targets were only shown with make -n; the
docker build and docker push commands themselves were not run. Clang isn't installed
either, which is why it only appears in dry runs.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Makefile tutorial here is tested end to end before publishing.