Conditionals and Portable Makefiles
How ifeq, ifdef and $(if) really work in GNU Make, why they run at parse time, and how to handle debug builds, OS detection, feature flags and BSD make.
By The Dark DebuggerUpdated 29 min read
This article covers Make's conditionals: ifeq, ifneq, ifdef, ifndef, and the
$(if ...) function. We'll use them for the jobs they're actually used for (debug and release
builds, detecting the operating system, optional features, checking for tools) and then look
at what changes when your Makefile has to run under BSD make too. You should be comfortable
with variables,
pattern rules and the
built-in functions, especially $(filter ...) and
$(shell ...).
Why conditionals, and the one rule that explains them
Sooner or later one Makefile has to serve several situations. A developer wants a debug build with symbols; CI wants an optimized release build. The same project is built on a Linux laptop, a Mac, and a Windows machine running Git Bash. Some users want an optional feature that pulls in extra code. Make's conditionals let one file adapt to all of that.
Almost every confusing thing about them comes from one rule, so here it is up front:
Make conditionals are evaluated while Make reads the Makefile, before any recipe runs. They decide which lines of the Makefile exist. They can't see anything that happens later: files a recipe creates, shell variables, or the target currently being built.
Keep that in mind and the rest of this article is detail.
ifeq and ifneq
ifeq compares two strings after expanding any variables in them:
ifeq ($(BUILD),debug)
OPT := -O0 -g
else
OPT := -O2
endififneq is the negation. Both accept three spellings, which are equivalent:
ifeq ($(BUILD),release)
ifeq "$(BUILD)" "release"
ifeq '$(BUILD)' 'release'The quoted forms are handy when a value contains a comma or parentheses. To pick between more
than two cases, chain them with else ifeq and close the whole chain with a single endif.
The final else is the place to reject values you don't support:
ifeq ($(BUILD),debug)
CFLAGS := -g -O0
else ifeq ($(BUILD),release)
CFLAGS := -O2
CPPFLAGS := -DNDEBUG
else
$(error BUILD must be 'debug' or 'release', not '$(BUILD)')
endifA typo then fails immediately with a clear message instead of quietly producing a release build:
make BUILD=debguMakefile:32: *** BUILD must be 'debug' or 'release', not 'debgu'. Stop.Indentation inside a conditional is allowed and helps readability, but use spaces, never a TAB. A line starting with a TAB is a recipe line to Make, as you'll see in Common mistakes.
Whitespace is part of the value
ifeq compares strings exactly. That bites in one very common situation, a comment on the
same line as an assignment:
BUILD ?= release # release or debug
ifeq ($(BUILD),release)
OPT := -O2
else
OPT := -O0 -g
endif
.PHONY: show
show:
@echo "BUILD='$(BUILD)' OPT=$(OPT)"make show
make show BUILD=releaseBUILD='release ' OPT=-O0 -g
BUILD='release' OPT=-O2Make strips whitespace before a value but keeps the spaces between the value and a #
comment. The default was release plus three spaces, the comparison failed, and the
"release" build got debug flags. Passing the same value on the command line worked, which
makes this a lovely bug to chase. Put comments on their own line, or compare
$(strip $(BUILD)).
ifdef and ifndef
ifdef NAME is true when the variable NAME has a non-empty value. Note the argument is a
variable name, not $(NAME). Two details make it less useful than it looks:
ifdef DEBUG
OPT := -O0 -g
else
OPT := -O2
endif
EXTRA_FLAGS =
FLAGS = $(EXTRA_FLAGS)
ifdef FLAGS
FLAGS_STATUS := defined
else
FLAGS_STATUS := not defined
endif
.PHONY: show
show:
@echo "DEBUG='$(DEBUG)' OPT=$(OPT)"
@echo "FLAGS='$(FLAGS)' is $(FLAGS_STATUS) for ifdef"make show
make show DEBUG=1
make show DEBUG=0
make show DEBUG=DEBUG='' OPT=-O2
FLAGS='' is defined for ifdef
DEBUG='1' OPT=-O0 -g
FLAGS='' is defined for ifdef
DEBUG='0' OPT=-O0 -g
FLAGS='' is defined for ifdef
DEBUG='' OPT=-O2
FLAGS='' is defined for ifdefDEBUG=0turns debug on.ifdefonly asks "is there a value?", and0is a value. Anyone who writesmake DEBUG=0expecting a release build gets the opposite.ifdefdoesn't expand the variable.FLAGSexpands to nothing, but its definition ($(EXTRA_FLAGS)) isn't empty, soifdef FLAGSis true.
My rule: use ifdef/ifndef only for "did anyone set this at all", such as a required
VERSION. For on/off switches, compare values with ifeq, or accept several spellings with
$(filter ...) (Exercise 2 does exactly that).
Parse time, not run time
Here's the rule from the top of the article causing real trouble. A deploy target should
upload the release tarball if there is one:
.PHONY: deploy
deploy: dist/app.tar.gz
ifeq ($(wildcard dist/app.tar.gz),)
@echo "no artifact found, skipping upload"
else
@echo "uploading dist/app.tar.gz"
endif
dist/app.tar.gz:
mkdir -p dist
tar -czf $@ srcmake deploy
make deploymkdir -p dist
tar -czf dist/app.tar.gz src
no artifact found, skipping upload
uploading dist/app.tar.gzOn the first run, Make built the tarball and then said there wasn't one. The ifeq had been
evaluated when Make read the file, while dist/ was still empty, so the recipe for deploy
was fixed as the "skipping" line before anything was built. On the second run the file
already existed at parse time.
The same thing happens with shell variables. This recipe looks reasonable and can never work:
.PHONY: release
release:
BRANCH=$$(git branch --show-current); echo "on branch $$BRANCH"
ifeq ($$BRANCH,main)
@echo "tagging a release from main"
else
@echo "refusing to release from a non-main branch"
endifmake releaseBRANCH=$(git branch --show-current); echo "on branch $BRANCH"
on branch main
refusing to release from a non-main branchWe're on main, and it refused. Make compared the literal text $BRANCH with main. The shell
variable only exists inside the shell that runs the first recipe line, long after Make chose
the lines.
There are two correct ways to write this, depending on when the decision should happen:
BRANCH := $(shell git branch --show-current)
.PHONY: release release-sh
# Parse time: $(shell ...) ran while make read the file.
release:
ifeq ($(BRANCH),main)
@echo "tagging a release from main"
else
@echo "refusing to release from '$(BRANCH)'"
@exit 1
endif
# Run time: the shell decides, when the recipe runs.
release-sh:
@branch=$$(git branch --show-current); \
if [ "$$branch" = main ]; then \
echo "tagging a release from main"; \
else \
echo "refusing to release from '$$branch'"; exit 1; \
fiOn a feature branch, both refuse:
git checkout -q -b feature/csv-export
make release
make release-shrefusing to release from 'feature/csv-export'
make: *** [Makefile:11: release] Error 1
refusing to release from 'feature/csv-export'
make: *** [Makefile:16: release-sh] Error 1The first version moves the question to parse time with $(shell ...); that's fine for
facts that don't change during the build, like the branch, the OS, or whether a tool is
installed. The second keeps the decision at run time in the shell; use it for anything a
recipe produces, like the tarball above. A Make conditional is never the right tool for
"did the previous step create this file?".
$(if) versus ifeq
$(if condition,then-part,else-part) is a function, not a directive. Its condition is
true when it expands to anything other than whitespace. On its own that only tests for
"non-empty"; combine it with $(filter ...) to test for a specific value:
$(if $(filter debug,$(BUILD)),-O0 -g,-O2).
The important difference is when it's evaluated. A directive runs once, at parse time. A
function runs whenever the text containing it is expanded, which for a recursive (=)
variable used in a recipe means at run time, per target. Target-specific variables show the
difference clearly:
BUILD ?= release
.PHONY: debug show
debug: BUILD := debug
debug: show
ifeq ($(BUILD),debug)
OPT := -O0 -g
else
OPT := -O2
endif
OPT_LAZY = $(if $(filter debug,$(BUILD)),-O0 -g,-O2)
show:
@echo "BUILD=$(BUILD) ifeq chose: $(OPT) if-function chose: $(OPT_LAZY)"make show
make debug
make show BUILD=debugBUILD=release ifeq chose: -O2 if-function chose: -O2
BUILD=debug ifeq chose: -O2 if-function chose: -O0 -g
BUILD=debug ifeq chose: -O0 -g if-function chose: -O0 -gdebug: BUILD := debug sets BUILD only while building debug and its prerequisites. The
ifeq had already run with BUILD=release and never saw it; the lazily expanded $(if) did.
A command-line value, on the other hand, exists from the start, so both agree.
| Use | When |
|---|---|
ifeq / ifneq | Choosing between blocks of variable definitions, rules or includes; validating input with $(error) |
ifdef / ifndef | "Was this variable set at all?" |
$(if ...) | A value inside an expression or a recipe line; anything that must see target-specific variables |
$(or ...), $(and ...) | First non-empty value ($(or $(MAKECMDGOALS),all)), or all-non-empty checks |
shell if in a recipe | Decisions about files or results that only exist at run time |
A complete example: fnvsum
The rest of the article uses one real project: fnvsum, a small C program that prints a
64-bit FNV-1a hash of each file you give it, a little like sha256sum. It has an optional JSON
output mode, and in debug builds it logs each file it hashes.
.
├── Makefile
├── data
│ ├── customers.csv
│ └── orders.csv
└── src
├── fnv.c
├── fnv.h
├── json.c
└── main.cThe C code uses #ifndef NDEBUG for the debug message and #ifdef WITH_JSON for the optional
format, which is how most C projects connect Make variables to code. Here is the Makefile:
# fnvsum: print 64-bit FNV-1a hashes of files.
# make release build
# make BUILD=debug debug build: -g -O0, debug messages on
# make WITH_JSON=1 add the --json output format
BUILD ?= release
WITH_JSON ?= 0
# ---- operating system ----------------------------------------------------
ifeq ($(OS),Windows_NT)
PLATFORM := windows
EXE := .exe
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
PLATFORM := linux
else ifeq ($(UNAME_S),Darwin)
PLATFORM := macos
else
PLATFORM := unknown
endif
EXE :=
endif
# ---- build mode ----------------------------------------------------------
ifeq ($(BUILD),debug)
CFLAGS := -g -O0
else ifeq ($(BUILD),release)
CFLAGS := -O2
CPPFLAGS := -DNDEBUG
else
$(error BUILD must be 'debug' or 'release', not '$(BUILD)')
endif
CFLAGS += -Wall -Wextra -std=c11
# ---- optional features ---------------------------------------------------
SRCS := src/main.c src/fnv.c
ifeq ($(WITH_JSON),1)
SRCS += src/json.c
CPPFLAGS += -DWITH_JSON
endif
# ---- required tools ------------------------------------------------------
ifeq ($(shell command -v $(CC)),)
$(error C compiler '$(CC)' not found; install it or set CC to another compiler)
endif
BUILD_DIR := build/$(PLATFORM)-$(BUILD)
OBJS := $(SRCS:src/%.c=$(BUILD_DIR)/%.o)
BIN := $(BUILD_DIR)/fnvsum$(EXE)
.PHONY: all info clean
all: $(BIN)
$(BIN): $(OBJS)
$(CC) $(LDFLAGS) $^ -o $@
$(BUILD_DIR)/%.o: src/%.c src/fnv.h | $(BUILD_DIR)
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
$(BUILD_DIR):
mkdir -p $@
info:
@echo "platform: $(PLATFORM) ($(if $(UNAME_S),uname says $(UNAME_S),OS=$(OS)))"
@echo "build: $(BUILD), json=$(WITH_JSON)"
@echo "flags: $(strip $(CPPFLAGS) $(CFLAGS))"
@echo "binary: $(BIN)"
clean:
rm -rf buildmake info shows what the conditionals decided, without building anything. An info target
like this is worth adding to any Makefile with more than one conditional:
make infoplatform: linux (uname says Linux)
build: release, json=0
flags: -DNDEBUG -O2 -Wall -Wextra -std=c11
binary: build/linux-release/fnvsumDetecting the operating system
Two sources of truth cover nearly every machine:
$(OS)is an environment variable that Windows sets toWindows_NT, and Make imports environment variables. It's present in cmd.exe, PowerShell, Git Bash and MSYS2 alike, which makes it the safest Windows test. Check it first, because a plain Windows shell has nouname.uname -snames the kernel everywhere else. Run it once with:=so the shell isn't started every time the variable is used.
| Environment | uname -s prints |
|---|---|
| Linux, including WSL | Linux |
| macOS | Darwin |
| Git Bash on Windows 11 | MINGW64_NT-10.0-26300 (the number is the Windows build) |
| FreeBSD | FreeBSD |
The Linux and Git Bash rows are from my test machines (OS was Windows_NT in Git Bash, as
expected); macOS and FreeBSD are their documented values. Since the Windows string changes
with every Windows build, match it with $(findstring MINGW,$(UNAME_S)) or rely on $(OS),
never ifeq against the full string.
I had no GNU Make on a native Windows machine for this article, but you can see what the Makefile would choose by setting the variable yourself, because command-line values override the environment:
make info OS=Windows_NTplatform: windows (OS=Windows_NT)
build: release, json=0
flags: -DNDEBUG -O2 -Wall -Wextra -std=c11
binary: build/windows-release/fnvsum.exeOS detection usually feeds three kinds of difference: file names (.exe, .dll versus
.so versus .dylib), libraries (-lpthread and -lrt on Linux, -framework flags on
macOS, -lws2_32 for sockets on Windows), and commands. That last one is the hard part. Native
Windows builds of GNU Make run recipes with cmd.exe unless they find a sh.exe on the
PATH, so rm -rf and mkdir -p don't exist there. If you need real native-Windows support,
I'd suggest requiring Git Bash or MSYS2 rather than writing every recipe twice.
Debug and release builds
make builds the release version; make BUILD=debug the debug version, which logs as it
works:
make
./build/linux-release/fnvsum data/orders.csv data/customers.csv
make BUILD=debug
./build/linux-debug/fnvsum data/orders.csvmkdir -p build/linux-release
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-release/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-release/fnv.o
cc build/linux-release/main.o build/linux-release/fnv.o -o build/linux-release/fnvsum
23656401183274df data/orders.csv
3bf5128957b02c3f data/customers.csv
mkdir -p build/linux-debug
cc -g -O0 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-debug/main.o
cc -g -O0 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-debug/fnv.o
cc build/linux-debug/main.o build/linux-debug/fnv.o -o build/linux-debug/fnvsum
debug: hashed data/orders.csv
23656401183274df data/orders.csvThe important design decision is BUILD_DIR := build/$(PLATFORM)-$(BUILD): each mode gets
its own object files. To see why, here's the same idea with a single build/ directory:
BUILD ?= release
ifeq ($(BUILD),debug)
CFLAGS := -g -O0
else
CFLAGS := -O2
CPPFLAGS := -DNDEBUG
endif
CFLAGS += -Wall -Wextra -std=c11
OBJS := build/main.o build/fnv.o
build/fnvsum: $(OBJS)
$(CC) $^ -o $@
build/%.o: src/%.c src/fnv.h
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@make
make BUILD=debug
./build/fnvsum data/orders.csvcc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/fnv.o
cc build/main.o build/fnv.o -o build/fnvsum
make: 'build/fnvsum' is up to date.The "debug" binary prints no debug line, because it is the release binary. Make tracks
files and timestamps, not the flags that produced them, so changing BUILD changed nothing it
could see. Separate output directories per configuration avoid the problem and let both builds
sit side by side, which is also what you want when comparing them.
Feature flags
WITH_JSON=1 is a typical feature flag: it adds a source file and a preprocessor define. Here
is the flag-tracking problem again, this time inside one build directory:
make
make WITH_JSON=1
./build/linux-release/fnvsum --json data/orders.csvmkdir -p build/linux-release
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-release/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-release/fnv.o
cc build/linux-release/main.o build/linux-release/fnv.o -o build/linux-release/fnvsum
cc -DNDEBUG -DWITH_JSON -O2 -Wall -Wextra -std=c11 -c src/json.c -o build/linux-release/json.o
cc build/linux-release/main.o build/linux-release/fnv.o build/linux-release/json.o -o build/linux-release/fnvsum
fnvsum: built without JSON supportMake compiled the new json.c and relinked, but main.o was "up to date" and still had
been compiled without -DWITH_JSON. The result links fine and doesn't work, the worst kind of
build bug. Two fixes, both in the exercises: put the feature in the build directory name
(Exercise 3), or record the flags in a file that the objects depend on (Exercise 5). Large
projects such as the Linux kernel do the second, storing the exact command line used for every
object.
Some conventions for flags that will save your users guesswork:
- Name them consistently (
WITH_X,USE_XorENABLE_X) and default them with?=at the top of the file, with a comment listing them. - Decide what "on" means and test for it explicitly:
ifeq ($(WITH_JSON),1). Don't useifdeffor switches, for theDEBUG=0reason above. - Show them in
make info.
Checking for required tools
A missing tool should fail at the start with a sentence, not halfway through with
command not found. $(shell command -v NAME) prints the tool's path, or nothing if it isn't
installed, so ifeq (...,) tests for absence. command -v is the POSIX way to ask; which
isn't guaranteed to exist and behaves differently between systems. fnvsum's check:
make CC=clangMakefile:45: *** C compiler 'clang' not found; install it or set CC to another compiler. Stop.To check a whole list at once, collect the missing names with $(foreach):
REQUIRED := gcc tar jq pandoc
MISSING := $(strip $(foreach t,$(REQUIRED),$(if $(shell command -v $(t)),,$(t))))
ifneq ($(MISSING),)
$(error missing required tools: $(MISSING))
endif
.PHONY: all
all:
@echo "all tools present"Makefile:5: *** missing required tools: pandoc. Stop.The $(strip) matters: without it the message read missing required tools: pandoc, with
one space per tool that was found. A top-level check like this blocks every target, which is
wrong when only one target needs the tool. Putting the check inside that target's recipe makes
it lazy:
.PHONY: all docs
all:
@echo "building the program (no pandoc needed)"
docs:
$(if $(shell command -v pandoc),,$(error 'make docs' needs pandoc; see https://pandoc.org/installing.html))
pandoc README.md -o build/README.htmlmake
make docsbuilding the program (no pandoc needed)
Makefile:6: *** 'make docs' needs pandoc; see https://pandoc.org/installing.html. Stop.MAKECMDGOALS: conditionals that depend on the goal
MAKECMDGOALS holds the targets named on the command line (empty if you just typed make).
Two problems come up often enough that this variable is the standard answer.
Expensive or generated includes. This Makefile includes a config.mk that it knows how to
generate. GNU Make rebuilds included makefiles before doing anything else, so:
include config.mk
.PHONY: all clean
all:
@echo "building with cc $(CC_VERSION)"
config.mk:
@echo "probing the toolchain..."
@echo "CC_VERSION := $$(cc -dumpversion)" > $@
clean:
rm -f config.mkmake cleanprobing the toolchain...
rm -f config.mkmake clean generated config.mk just to delete it. Here that costs a second; in a project
whose configure step takes a minute, or fails when a dependency is missing, it stops you
cleaning up at all. Wrapping the include in a goal check skips it for clean and help:
ifeq ($(filter clean help,$(MAKECMDGOALS)),)
include config.mk
endifGoal-specific requirements. The same file continues with a check that only applies when
deploy is requested, followed by the rules:
ifneq ($(filter deploy,$(MAKECMDGOALS)),)
ifndef ENV
$(error deploy needs ENV, e.g. make deploy ENV=staging)
endif
endif
.PHONY: all clean help deploy release
all:
@echo "building with cc $(CC_VERSION)"
config.mk:
@echo "probing the toolchain..."
@echo "CC_VERSION := $$(cc -dumpversion)" > $@
help:
@echo "targets: all clean deploy release"
deploy: all
@echo "deploying to $(ENV)"
release: deploy
clean:
rm -f config.mkmake clean
make deploy
make deploy ENV=staging
make releaserm -f config.mk
Makefile:7: *** deploy needs ENV, e.g. make deploy ENV=staging. Stop.
probing the toolchain...
building with cc 13
deploying to staging
building with cc 13
deploying to make clean no longer probes, and make deploy fails before doing any work. But look at the
last command: make release deployed to an empty environment. release depends on deploy,
yet deploy wasn't named on the command line, so MAKECMDGOALS didn't contain it. That's the
limit of this trick: it knows what the user typed, not what will be built. For a check that
must hold however a target is reached, put it in that target's recipe, like the require
function in Make as a Task Runner.
GNU make, BSD make, and portable Makefiles
Everything above is GNU Make syntax. FreeBSD, OpenBSD and NetBSD ship a different make
whose conditionals look like the C preprocessor. To test this
article I ran bmake, the portable version of NetBSD's make. Here's the debug/release logic in
its dialect:
BUILD ?= release
UNAME_S != uname -s
.if ${BUILD} == "debug"
CFLAGS = -g -O0
.elif ${BUILD} == "release"
CFLAGS = -O2 -DNDEBUG
.else
.error BUILD must be debug or release
.endif
.if ${UNAME_S} == "Linux" || ${UNAME_S} == "FreeBSD"
PLATFORM = ${UNAME_S:tl}
.endif
show:
@echo "platform=${PLATFORM} CFLAGS=${CFLAGS}"bmake
bmake BUILD=debug
bmake BUILD=fastplatform=linux CFLAGS=-O2 -DNDEBUG
platform=linux CFLAGS=-g -O0
bmake: "[…]/fnvsum/Makefile" line 9: BUILD must be debug or release(I shortened the absolute path bmake prints.) BSD conditionals can use ||, && and !
directly, and ${UNAME_S:tl} is a variable modifier that lowercases the value. Neither make
understands the other's conditionals. GNU Make on the BSD file:
Makefile:4: *** missing separator. Stop.and bmake on the GNU fnvsum Makefile:
bmake: "[…]/fnvsum/Makefile" line 10: Missing dependency operator
bmake: "[…]/fnvsum/Makefile" line 13: Need an operator
[…]
bmake: Fatal errors encountered -- cannot continueLine 10 is the ifeq ($(OS),Windows_NT). If you see "Need an operator" on a BSD system, you
are almost certainly running a GNU Makefile with the system make. Install GNU Make from
packages and run gmake.
What's actually portable
A few things work in both, and I tested each of these with GNU Make 4.3 and bmake:
UNAME_S != uname -s
CC = cc
CFLAGS = -O2 -Wall
fnvsum: src/main.c src/fnv.c src/fnv.h
$(CC) $(CFLAGS) -o fnvsum src/main.c src/fnv.c
@echo "built fnvsum for $(UNAME_S)"
clean:
rm -f fnvsummake
bmakecc -O2 -Wall -o fnvsum src/main.c src/fnv.c
built fnvsum for Linux
cc -O2 -Wall -o fnvsum src/main.c src/fnv.c
built fnvsum for Linux(I ran make clean between the two.) VAR != command assigns a command's output in both
makes; GNU Make has supported it since 4.0. Explicit rules, $(VAR) references and $@ all
work too. Small differences hide everywhere else. $^ (all prerequisites) is GNU-only:
fnvsum: src/main.c src/fnv.c
cc -O2 -o $@ $^
clean:
rm -f fnvsummake
make clean
bmakecc -O2 -o fnvsum src/main.c src/fnv.c
rm -f fnvsum
cc -O2 -o fnvsum
x86_64-linux-gnu-gcc-13: fatal error: no input files
compilation terminated.
*** Error code 1
Stop.
bmake: stopped in […]/fnvsumbmake expanded $^ to nothing (its spelling is $>) and the compiler got no input files.
| Feature | GNU Make | BSD make | Portable? |
|---|---|---|---|
| Conditionals | ifeq, ifdef, else ifeq, endif | .if, .ifdef, .elif, .endif | No |
| Include | include file, -include file | .include "file", .-include "file" | No (write include only for GNU) |
| Shell output | $(shell cmd), VAR != cmd (4.0+) | VAR != cmd | != only |
| Functions | $(patsubst), $(filter), $(foreach), ... | Variable modifiers: ${VAR:S/a/b/}, ${VAR:M*.c} | No |
| Pattern rules | %.o: %.c | Suffix rules (.c.o:) | Suffix rules only |
| All prerequisites | $^ | $> | No; list files explicitly |
| Error message | $(error text) | .error text | No |
My recommendation: don't try to make a non-trivial Makefile portable between the two. Write
GNU Make, say so in the README, and consider naming the file GNUmakefile. GNU Make reads
GNUmakefile before Makefile; BSD make ignores it, so BSD users get a clear "no makefile"
error instead of a screenful of parse errors. Projects that truly must build with both makes
either keep their Makefiles deliberately primitive (explicit rules, !=, no functions) or
generate them with a configure script.
Where you'll use this
- Cross-platform command-line tools. OS detection picks the executable suffix, libraries
and install paths, as in
fnvsum. - Build modes in CI. One Makefile, many configurations: a debug build for the test job, a
release build for the artifact. Because every mode has its own build directory, a CI cache
of
build/keeps all of them warm. - Optional dependencies. Real C projects expose switches like these on the command line;
Redis, for example, is built with
make BUILD_TLS=yesto include TLS support, and the Linux kernel usesmake V=1for verbose output andmake O=dirfor an output directory, each implemented with conditionals on those variables. - Environment and tool checks. Failing fast with "pandoc is required for make docs" saves a newcomer from an unreadable error twenty lines into a build.
Here is the build-matrix loop you might run locally before pushing, with every configuration built side by side:
make clean
for mode in debug release; do make --no-print-directory BUILD=$mode; done
tree --noreport buildrm -rf build
mkdir -p build/linux-debug
cc -g -O0 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-debug/main.o
cc -g -O0 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-debug/fnv.o
cc build/linux-debug/main.o build/linux-debug/fnv.o -o build/linux-debug/fnvsum
mkdir -p build/linux-release
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-release/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-release/fnv.o
cc build/linux-release/main.o build/linux-release/fnv.o -o build/linux-release/fnvsum
build
├── linux-debug
│ ├── fnv.o
│ ├── fnvsum
│ └── main.o
└── linux-release
├── fnv.o
├── fnvsum
└── main.oRun the loop a second time and nothing is rebuilt, because both trees are up to date:
make: Nothing to be done for 'all'.
make: Nothing to be done for 'all'.Common mistakes
A conditional indented with a TAB inside a recipe
Conditionals are allowed between recipe lines, but they must start at the left margin (or be indented with spaces). Indented with a TAB, they become recipe lines and go to the shell:
BUILD ?= release
.PHONY: package
package:
@echo "packaging the $(BUILD) build"
ifeq ($(BUILD),debug)
@echo "including debug symbols"
endifmake packagepackaging the release build
ifeq (release,debug)
/bin/sh: 1: Syntax error: word unexpected (expecting ")")
make: *** [Makefile:6: package] Error 2/bin/sh received ifeq (release,debug), which isn't shell syntax. The tell-tale sign is
the conditional itself appearing in the output. Move ifeq, else and endif to column 0,
as in the deploy example earlier.
"missing 'endif'"
BUILD ?= release
ifeq ($(BUILD),debug)
CFLAGS := -O0 -g
else
CFLAGS := -O2
.PHONY: show
show:
@echo "CFLAGS=$(CFLAGS)"Makefile:11: *** missing 'endif'. Stop.Make reports the last line of the file, not the ifeq that was left open, because only at
the end of the file does it know the endif never came. In a long Makefile, search upwards
for ifeq/ifdef lines and count them against the endifs. An editor that folds Makefile
conditionals helps.
A value that looks right but doesn't match
If an ifeq you're sure should be true isn't, print the value with quotes around it:
$(info BUILD='$(BUILD)'). Trailing spaces from a same-line comment (shown earlier) and
mixed case (Release versus release) are the usual causes. $(strip) fixes the first;
for the second, decide on lowercase and document it.
The decision doesn't see a file or variable from earlier in the build
If a conditional seems to be "one run behind", like the deploy that only found its tarball
on the second run, it depends on something that happens during the build. Move that decision
into the recipe (shell if) or make the file a prerequisite and let Make's normal rules
handle it.
Summary
ifeq,ifneq,ifdefandifndefare evaluated once, while Make reads the Makefile. They select lines; they can't see recipe results, shell variables or target-specific variables.ifeqcompares exact strings. A comment on an assignment line leaves trailing spaces in the value; keep comments on their own line or use$(strip).ifdeftests for a non-empty definition without expanding it, soDEBUG=0counts as set. Useifeqor$(filter)for on/off switches.$(if)is a function, evaluated whenever its text is expanded, so it can see target-specific variables. Pair it with$(filter)to test equality.- Detect Windows with
$(OS)(Windows_NT) first, thenuname -sonce via:=. Use$(error)in a finalelseto reject unsupported values. - Give each build configuration its own output directory; Make doesn't notice when flags change. Feature flags need the same care.
MAKECMDGOALSlets you skip work forcleanorhelpand check variables for specific goals, but it only knows what was typed, not what will be built.- GNU and BSD make conditionals are incompatible. Write GNU Make, say so, and use
gmakeon the BSDs;VAR != commandis one of the few portable extras.
Exercises
The exercises start from the fnvsum Makefile. My combined solution, with all five changes,
is the one whose output appears below.
Add BUILD=size, which compiles with -Os and defines NDEBUG, into its own build
directory. Update the error message, then check it with make BUILD=size info and
make BUILD=size.
Show Solution
Add one more branch to the chain, before the final else:
else ifeq ($(BUILD),size)
CFLAGS := -Os
CPPFLAGS := -DNDEBUG
else
$(error BUILD must be 'debug', 'release' or 'size', not '$(BUILD)')
endifmake BUILD=size info
make BUILD=sizeplatform: linux (uname says Linux)
build: size, json=0
flags: -DNDEBUG -Os -Wall -Wextra -std=c11
binary: build/linux-size/fnvsum
mkdir -p build/linux-size
cc -DNDEBUG -Os -Wall -Wextra -std=c11 -c src/main.c -o build/linux-size/main.o
cc -DNDEBUG -Os -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-size/fnv.o
cc build/linux-size/main.o build/linux-size/fnv.o -o build/linux-size/fnvsumThe build directory needed no change: it's derived from $(BUILD). (The double space before
-c comes from the empty EXTRA_CFLAGS that Exercise 5 adds.)
Rewrite the ifdef DEBUG example so that DEBUG=1, DEBUG=yes and DEBUG=true turn debug
flags on, and anything else, including DEBUG=0 and no value at all, leaves them off.
Hint
$(filter 1 yes true,$(DEBUG)) returns DEBUG's value if it's one of those words, and
nothing otherwise.
Show Solution
ifneq ($(filter 1 yes true,$(DEBUG)),)
OPT := -O0 -g
else
OPT := -O2
endif
.PHONY: show
show:
@echo "DEBUG='$(DEBUG)' OPT=$(OPT)"make show DEBUG=0
make show DEBUG=yes
make showDEBUG='0' OPT=-O2
DEBUG='yes' OPT=-O0 -g
DEBUG='' OPT=-O2ifneq (...,) reads as "if this is not empty". Accepting a small, explicit list of "on"
words is friendlier than ifdef and can't be triggered by accident.
Change BUILD_DIR so that WITH_JSON=1 builds go into their own directory (for example
build/linux-release-json). Then reproduce the scenario from Feature flags:
make, then make WITH_JSON=1, and check that --json works.
Show Solution
BUILD_DIR := build/$(PLATFORM)-$(BUILD)$(if $(filter 1,$(WITH_JSON)),-json)make
make WITH_JSON=1
./build/linux-release-json/fnvsum --json data/orders.csv data/customers.csv[…]
mkdir -p build/linux-release-json
cc -DNDEBUG -DWITH_JSON -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-release-json/main.o
cc -DNDEBUG -DWITH_JSON -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-release-json/fnv.o
cc -DNDEBUG -DWITH_JSON -O2 -Wall -Wextra -std=c11 -c src/json.c -o build/linux-release-json/json.o
cc build/linux-release-json/main.o build/linux-release-json/fnv.o build/linux-release-json/json.o -o build/linux-release-json/fnvsum
[{"file": "data/orders.csv", "fnv1a": "23656401183274df"},
{"file": "data/customers.csv", "fnv1a": "3bf5128957b02c3f"}]$(if) appends -json only when the flag is on. Every object for the JSON build is compiled
fresh with -DWITH_JSON. The downside of this approach is a directory per combination of
flags, which grows quickly with three or four flags; Exercise 5 solves it differently.
make info CC=clang currently fails on a machine without clang, although info compiles
nothing. Make the compiler check run only when a goal other than info or clean is
requested, remembering that plain make means all. Test make info CC=clang,
make CC=clang and make info all CC=clang.
Hint
$(or $(MAKECMDGOALS),all) gives you the goal list with the default filled in, and
$(filter-out ...) removes the harmless goals from it.
Show Solution
ifneq ($(filter-out info clean,$(or $(MAKECMDGOALS),all)),)
ifeq ($(shell command -v $(CC)),)
$(error C compiler '$(CC)' not found; install it or set CC to another compiler)
endif
endifmake info CC=clang
make CC=clang
make info all CC=clangplatform: linux (uname says Linux)
build: release, json=0
flags: -DNDEBUG -O2 -Wall -Wextra -std=c11
binary: build/linux-release/fnvsum
Makefile:49: *** C compiler 'clang' not found; install it or set CC to another compiler. Stop.
Makefile:49: *** C compiler 'clang' not found; install it or set CC to another compiler. Stop.Checking "is there any goal left after removing the harmless ones" is more robust than
checking "is the goal info": it handles make info all, and make with no goal at all.
Add an EXTRA_CFLAGS variable that is appended to CFLAGS. Then make every object depend on
a file, $(BUILD_DIR)/flags.txt, that holds the current compiler flags and is only rewritten
when they differ from the previous build. make EXTRA_CFLAGS=-fno-omit-frame-pointer should
recompile everything; running it again should compile nothing; plain make afterwards should
recompile again.
Hint
Give the flags file a prerequisite that is always out of date (an empty phony target, by
convention called FORCE), so its recipe always runs. Inside, compare with cmp -s and only
write when different. GNU Make re-checks a target's timestamp after its recipe runs.
Show Solution
CFLAGS += -Wall -Wextra -std=c11 $(EXTRA_CFLAGS)FLAGS_FILE := $(BUILD_DIR)/flags.txt
.PHONY: all info clean FORCE
all: $(BIN)
$(BIN): $(OBJS)
$(CC) $(LDFLAGS) $^ -o $@
$(BUILD_DIR)/%.o: src/%.c src/fnv.h $(FLAGS_FILE) | $(BUILD_DIR)
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
# Rewritten only when the flags differ from the last build.
$(FLAGS_FILE): FORCE | $(BUILD_DIR)
@echo '$(CPPFLAGS) $(CFLAGS)' | cmp -s - $@ || echo '$(CPPFLAGS) $(CFLAGS)' > $@With a release build already in place:
make EXTRA_CFLAGS=-fno-omit-frame-pointer
make EXTRA_CFLAGS=-fno-omit-frame-pointer
cat build/linux-release/flags.txt
makecc -DNDEBUG -O2 -Wall -Wextra -std=c11 -fno-omit-frame-pointer -c src/main.c -o build/linux-release/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -fno-omit-frame-pointer -c src/fnv.c -o build/linux-release/fnv.o
cc build/linux-release/main.o build/linux-release/fnv.o -o build/linux-release/fnvsum
-DNDEBUG -O2 -Wall -Wextra -std=c11 -fno-omit-frame-pointer
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/main.c -o build/linux-release/main.o
cc -DNDEBUG -O2 -Wall -Wextra -std=c11 -c src/fnv.c -o build/linux-release/fnv.o
cc build/linux-release/main.o build/linux-release/fnv.o -o build/linux-release/fnvsumThe second command printed nothing at all: the flags recipe ran (it always does) but left the
file untouched, and since Make checks the file's timestamp again after running its recipe,
nothing depending on it was rebuilt. Only real changes to the flags rewrite flags.txt and
cascade into recompiles. The FORCE target has no recipe and no prerequisites, which is the
traditional way to say "always run this rule".
Tested with: GNU Make 4.3, GCC 13.3.0 and GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), and
bmake 20200710 (Debian's package of NetBSD make, unpacked into a scratch directory), November
2026. Every Makefile and command above was run as shown; I shortened the absolute paths in
bmake's messages to […]. The Git Bash uname -s value and OS=Windows_NT were read on a
Windows 11 machine; there was no native-Windows GNU Make or macOS machine for this article, so
the Windows branch was exercised with make info OS=Windows_NT and the macOS Darwin branch
was not run.
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.