Built-in Functions

GNU Make's built-in functions for text, file names, loops, conditions, shell commands and debugging, applied to discovering sources and generating per-module build rules.

By The Dark DebuggerUpdated 23 min read

GNU Make has a small functional language built in: functions that transform lists of words, pick apart file names, loop, branch, run shell commands and even generate new rules. This article covers the ones you'll actually use, with the output of each, and finishes with a Makefile that discovers a project's modules from the directory tree and builds a static library per module without listing a single file. It assumes you know variables (Variables and How Make Expands Them) and pattern rules with automatic variables (Pattern Rules).

Why functions

A Makefile that lists its sources by hand goes stale the day someone adds a file and forgets the Makefile. Then the build breaks with an undefined reference, or worse, keeps "working" with an old object. Functions let the Makefile ask the filesystem what exists and derive everything else (object names, library names, per-module rules) from that.

Our example is a small inventory service in C, split into modules by directory:

.
├── docs
│   └── README
├── include
│   ├── net
│   │   ├── http.h
│   │   └── tls.h
│   ├── store
│   │   ├── cache.h
│   │   └── disk.h
│   └── util
│       ├── log.h
│       └── strbuf.h
├── src
│   ├── main.c
│   ├── net
│   │   ├── http.c
│   │   └── tls.c
│   ├── store
│   │   ├── cache.c
│   │   └── disk.c
│   └── util
│       ├── log.c
│       └── strbuf.c
└── tests
    ├── test_cache.c
    └── test_http.c

How a function call looks

$(function-name argument1,argument2,...)

The name is followed by a space, and arguments are separated by commas. Make expands the arguments first, then calls the function, and the call is replaced by its result, just like a variable reference. Most results are space-separated lists of words.

To see results while experimenting, use $(info ...), which prints its argument when the Makefile is read. Each demo file below ends with all: ; @:, a do-nothing target, so Make has something to build after printing. (: is the shell's no-op command, and the ; puts the recipe on the rule line.)

One rule to remember from the start: don't put spaces after the commas. Whitespace after a comma becomes part of the next argument, and in some functions that changes the result. Common mistakes has the evidence.

Text functions

These treat a value as a list of words separated by whitespace:

SRCS   := src/main.c src/net/http.c src/net/tls.c src/store/cache.c src/util/log.c
CFLAGS := -Wall   -O2    -g
 
$(info subst:       $(subst /,_,$(SRCS)))
$(info patsubst:    $(patsubst src/%.c,obj/%.o,$(SRCS)))
$(info subst ref:   $(SRCS:src/%.c=obj/%.o))
$(info strip:       [$(CFLAGS)] -> [$(strip $(CFLAGS))])
$(info findstring:  [$(findstring -O2,$(CFLAGS))] [$(findstring -O3,$(CFLAGS))])
$(info filter:      $(filter src/net/%,$(SRCS)))
$(info filter-out:  $(filter-out src/main.c,$(SRCS)))
$(info sort:        $(sort util net store net util))
$(info words:       $(words $(SRCS)))
$(info word 2:      $(word 2,$(SRCS)))
$(info wordlist:    $(wordlist 2,3,$(SRCS)))
$(info firstword:   $(firstword $(SRCS)))
$(info lastword:    $(lastword $(SRCS)))
 
all: ; @:
make -f text.mk
subst:       src_main.c src_net_http.c src_net_tls.c src_store_cache.c src_util_log.c
patsubst:    obj/main.o obj/net/http.o obj/net/tls.o obj/store/cache.o obj/util/log.o
subst ref:   obj/main.o obj/net/http.o obj/net/tls.o obj/store/cache.o obj/util/log.o
strip:       [-Wall   -O2    -g] -> [-Wall -O2 -g]
findstring:  [-O2] []
filter:      src/net/http.c src/net/tls.c
filter-out:  src/net/http.c src/net/tls.c src/store/cache.c src/util/log.c
sort:        net store util
words:       5
word 2:      src/net/http.c
wordlist:    src/net/http.c src/net/tls.c
firstword:   src/main.c
lastword:    src/util/log.c
FunctionWhat it doesWhere you'll use it
$(subst from,to,text)Literal replace, everywhere in the textTurning paths into flat names
$(patsubst pattern,replacement,text)Replace whole words matching a % patternSource list to object list
$(VAR:pattern=replacement)Shorthand for patsubst on a variableSame, shorter
$(strip text)Trim and collapse whitespaceCleaning values before comparing them
$(findstring find,text)find if it occurs anywhere, else emptyQuick "does CFLAGS mention -O2?" checks
$(filter patterns,text)Keep words matching any patternPicking out .c files, one module
$(filter-out patterns,text)Drop words matching any patternEverything except main.c
$(sort list)Sort and remove duplicatesUnique module names
$(words text), $(word n,text), $(wordlist s,e,text)Count, pick, slice (1-based)Counts in messages, picking a default
$(firstword text), $(lastword text)First or last wordThe most recently included file

filter-out src/main.c deserves a note: it's how you link test programs against all of a project's code except the file that contains main(). sort is the standard way to deduplicate a list, since Make has no separate "unique" function.

File name functions

FILES := src/net/http.c include/net/http.h docs/README Makefile
 
$(info dir:         $(dir $(FILES)))
$(info notdir:      $(notdir $(FILES)))
$(info suffix:      $(suffix $(FILES)))
$(info basename:    $(basename $(FILES)))
$(info addprefix:   $(addprefix build/,main.o http.o))
$(info addsuffix:   $(addsuffix .o,main http))
$(info wildcard:    $(wildcard src/*.c src/*/*.c))
$(info no match:    [$(wildcard src/*.cpp)])
$(info modules:     $(wildcard src/*/))
$(info abspath:     $(abspath /usr/share/../lib/missing.so))
$(info realpath:    [$(realpath /usr/lib/missing.so)] [$(realpath /usr/bin/python3)])
 
all: ; @:
make -f names.mk
dir:         src/net/ include/net/ docs/ ./
notdir:      http.c http.h README Makefile
suffix:      .c .h
basename:    src/net/http include/net/http docs/README Makefile
addprefix:   build/main.o build/http.o
addsuffix:   main.o http.o
wildcard:    src/main.c src/net/http.c src/net/tls.c src/store/cache.c src/store/disk.c src/util/log.c src/util/strbuf.c
no match:    []
modules:     src/net/ src/store/ src/util/
abspath:     /usr/lib/missing.so
realpath:    [] [/usr/bin/python3.12]

The details that matter:

  • dir keeps the trailing slash and returns ./ for a bare name. suffix returns nothing for names without a dot, so the lists can come back shorter than the input.
  • wildcard returns only files that exist right now, sorted, and an empty string (not an error) when nothing matches. It has no recursive **. Use one pattern per depth, as above, or $(shell find ...) for deep trees.
  • $(wildcard src/*/) with a trailing slash lists directories. That's how we'll discover modules.
  • abspath cleans up .. and makes a path absolute without looking at the disk, so it works for files that don't exist yet. realpath asks the filesystem: it resolves symlinks (here python3 points to python3.12) and returns empty for anything missing.

foreach: loops

$(foreach var,list,text) expands text once per word in list, with var set to that word, and joins the results with spaces:

MODULES := $(notdir $(patsubst %/,%,$(wildcard src/*/)))
 
$(info modules:     $(MODULES))
$(info libraries:   $(foreach m,$(MODULES),lib/lib$(m).a))
$(info sources:     $(foreach m,$(MODULES),$(wildcard src/$(m)/*.c)))
make -f loops.mk
modules:     net store util
libraries:   lib/libnet.a lib/libstore.a lib/libutil.a
sources:     src/net/http.c src/net/tls.c src/store/cache.c src/store/disk.c src/util/log.c src/util/strbuf.c

The MODULES line reads inside out: list the directories (src/net/ ...), strip the trailing slash with patsubst, and keep only the last path component with notdir. Nesting like this is normal in Makefiles. Read it from the innermost call outward.

call: your own functions

A recursive variable that refers to $(1), $(2) and so on works as a function. $(call name,arg1,arg2) expands it with those arguments filled in. These lines follow the foreach ones in loops.mk, and printed the rest of its output:

module_srcs = $(wildcard src/$(1)/*.c)
module_objs = $(patsubst src/%.c,obj/%.o,$(call module_srcs,$(1)))
 
$(info net objects: $(call module_objs,net))
$(info all objects: $(foreach m,$(MODULES),$(call module_objs,$(m))))
net objects: obj/net/http.o obj/net/tls.o
all objects: obj/net/http.o obj/net/tls.o obj/store/cache.o obj/store/disk.o obj/util/log.o obj/util/strbuf.o

These must be defined with =, not :=. With :=, $(1) would be expanded (to nothing) at definition time. Use call when the same transformation appears more than twice; a named function like module_objs documents intent better than a repeated patsubst.

if, or, and: conditions

Make has no booleans. An empty string is false and anything else is true.

  • $(if condition,then-part,else-part) returns then-part if the condition expands to non-empty text.
  • $(or a,b,...) returns the first non-empty argument.
  • $(and a,b,...) returns the last argument if all are non-empty, otherwise empty.
OPT_FLAGS := $(if $(DEBUG),-O0 -g,-O2)
SANITIZE  := $(and $(DEBUG),$(ASAN),-fsanitize=address)
CC_NAME   := $(or $(CC_OVERRIDE),$(CC))
 
$(info DEBUG=[$(DEBUG)] ASAN=[$(ASAN)])
$(info OPT_FLAGS: $(OPT_FLAGS))
$(info SANITIZE:  [$(SANITIZE)])
$(info CC_NAME:   $(CC_NAME))
 
all: ; @:
make -f cond.mk
make -f cond.mk DEBUG=1 ASAN=1
make -f cond.mk CC_OVERRIDE=clang
make -f cond.mk DEBUG=0
DEBUG=[] ASAN=[]
OPT_FLAGS: -O2
SANITIZE:  []
CC_NAME:   cc
DEBUG=[1] ASAN=[1]
OPT_FLAGS: -O0 -g
SANITIZE:  [-fsanitize=address]
CC_NAME:   cc
DEBUG=[] ASAN=[]
OPT_FLAGS: -O2
SANITIZE:  []
CC_NAME:   clang
DEBUG=[0] ASAN=[]
OPT_FLAGS: -O0 -g
SANITIZE:  []
CC_NAME:   cc

Look at the last one: DEBUG=0 turned debugging on, because 0 is a non-empty string. People will type DEBUG=0 and DEBUG=no, so if a flag is user-facing, test for the values you mean with filter:

is_true = $(filter 1 yes true,$(1))
 
OPT_FLAGS := $(if $(call is_true,$(DEBUG)),-O0 -g,-O2)
make -f cond-fixed.mk DEBUG=0
make -f cond-fixed.mk DEBUG=yes
DEBUG=[0] OPT_FLAGS: -O2
DEBUG=[yes] OPT_FLAGS: -O0 -g

Whole blocks of Makefile that depend on a condition use ifeq/ifdef instead. Those are covered in Conditionals and Portable Makefiles.

shell: running commands while the Makefile is read

$(shell command) runs a command when the line is expanded and returns its output, with newlines turned into spaces:

GIT_SHA  := $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
BRANCH   := $(shell git rev-parse --abbrev-ref HEAD)
C_FILES  := $(shell find src -name '*.c' | sort)
NOPE     := $(shell ls no-such-dir 2>/dev/null)
STATUS   := $(.SHELLSTATUS)
 
$(info GIT_SHA: $(GIT_SHA))
$(info BRANCH:  $(BRANCH))
$(info C_FILES: $(C_FILES))
$(info NOPE:    [$(NOPE)] exit status $(STATUS))
 
all: ; @:
make -f shell.mk
GIT_SHA: dac6246
BRANCH:  main
C_FILES: src/main.c src/net/http.c src/net/tls.c src/store/cache.c src/store/disk.c src/util/log.c src/util/strbuf.c
NOPE:    [] exit status 2

A failing command doesn't stop Make. $(shell) just returns whatever was printed, here nothing. If you need to know, .SHELLSTATUS (GNU Make 4.2+) holds the exit status of the last $(shell) call. The || echo unknown on the first line is the usual way to give a fallback, for example when building from a tarball with no Git history.

Always assign $(shell ...) with :=. With =, the command runs again every time the variable is referenced. This file logs each run:

STAMP_LAZY  = $(shell echo lazy >> shell-calls.log; date +%T.%N)
STAMP_ONCE := $(shell echo once >> shell-calls.log; date +%T.%N)
 
show:
	@echo "lazy: $(STAMP_LAZY) $(STAMP_LAZY) $(STAMP_LAZY)"
	@echo "once: $(STAMP_ONCE) $(STAMP_ONCE) $(STAMP_ONCE)"
	@sort shell-calls.log | uniq -c
make -f shellcount.mk
lazy: 21:51:33.235746188 21:51:33.237650221 21:51:33.240251562
once: 21:51:33.233365573 21:51:33.233365573 21:51:33.233365573
      3 lazy
      1 once

Three references, three runs, three different timestamps. With a slow command like git describe or pkg-config in a variable used in every compile line, that adds up to seconds per build, and you can get different values within one build.

eval: generating rules

$(eval text) takes text and parses it as Makefile syntax, as if it had been written in the file. Combined with define and call, it generates rules from data. Here is a template for "every module becomes a static library":

define MODULE_RULES
$(1)_OBJS := $$(patsubst src/%.c,obj/%.o,$$(wildcard src/$(1)/*.c))
lib/lib$(1).a: $$($(1)_OBJS) | lib
	$$(AR) rcs $$@ $$^
endef
$(foreach m,$(MODULES),$(eval $(call MODULE_RULES,$(m))))

The doubled $$ is the part that confuses everyone. The text goes through two expansions: once by call, which fills in $(1), and again when eval parses the result. $(1) should be replaced in the first pass, so it has one $. Everything that must survive to the second pass, $@, $^, $(AR) and the module's own variables, gets $$ so that the first pass turns it into a single $.

When an eval template misbehaves, print what it generates. I added this line temporarily to the end of the Makefile:

tail -n 1 Makefile
make print-MODULES
$(info $(call MODULE_RULES,net))
net_OBJS := $(patsubst src/%.c,obj/%.o,$(wildcard src/net/*.c))
lib/libnet.a: $(net_OBJS) | lib
	$(AR) rcs $@ $^
MODULES = net store util

That's exactly the text eval receives for the net module: an ordinary variable and an ordinary rule. If it looks right here, it will work. If a $@ is missing, you needed one more $. (print-MODULES is a small helper target from the full Makefile below.)

My advice: reach for eval only when pattern rules can't express the structure, as with "one library per directory" here. Each use makes the Makefile harder to read, and the error messages point at the $(foreach ...) line, not at the generated rule.

info, warning, error: debugging and guard rails

  • $(info text) prints text.
  • $(warning text) prints it with the file name and line number.
  • $(error text) prints it with the location and stops Make.

They run whenever they're expanded. At the top level of a Makefile, that's when the file is read. Inside a recipe, it's only when that recipe is about to run, which makes error inside a recipe a clean way to validate a target's inputs:

SRCS := $(wildcard src/*/*.c)
$(info found $(words $(SRCS)) source files)
$(if $(filter src/legacy/%,$(SRCS)),$(warning src/legacy is deprecated and will be removed))
 
.PHONY: build deploy
 
build:
	@echo "building $(words $(SRCS)) files"
 
deploy:
	$(if $(DEPLOY_ENV),,$(error DEPLOY_ENV is not set; run: make deploy DEPLOY_ENV=staging))
	@echo "deploying to $(DEPLOY_ENV)"

With a src/legacy/ directory present:

make -f debug.mk build
make -f debug.mk deploy
make -f debug.mk deploy DEPLOY_ENV=staging
found 7 source files
debug.mk:3: src/legacy is deprecated and will be removed
building 7 files
found 7 source files
debug.mk:3: src/legacy is deprecated and will be removed
debug.mk:11: *** DEPLOY_ENV is not set; run: make deploy DEPLOY_ENV=staging.  Stop.
found 7 source files
debug.mk:3: src/legacy is deprecated and will be removed
deploying to staging

make build never tripped the DEPLOY_ENV check, because the deploy recipe was never expanded. Put the same $(error) at the top level and every target, including make clean, would demand a deploy environment.

origin and flavor: where a variable came from

$(origin VAR) reports where a variable's value came from, and $(flavor VAR) whether it's recursive or simple:

CFLAGS  := -O2
LDFLAGS  = -L/opt/lib
 
$(info CC      origin=$(origin CC) flavor=$(flavor CC) value=$(CC))
$(info CFLAGS  origin=$(origin CFLAGS) flavor=$(flavor CFLAGS))
$(info LDFLAGS origin=$(origin LDFLAGS) flavor=$(flavor LDFLAGS))
$(info HOME    origin=$(origin HOME))
$(info PREFIX  origin=$(origin PREFIX))
$(info NOPE    origin=$(origin NOPE) flavor=$(flavor NOPE))
 
all:
	@echo "inside a recipe, @ has origin $(origin @)"
make -f origin.mk
PREFIX=/opt/inventory make -f origin.mk CFLAGS=-Os
CC      origin=default flavor=recursive value=cc
CFLAGS  origin=file flavor=simple
LDFLAGS origin=file flavor=recursive
HOME    origin=environment
PREFIX  origin=undefined
NOPE    origin=undefined flavor=undefined
inside a recipe, @ has origin automatic
CC      origin=default flavor=recursive value=cc
CFLAGS  origin=command line flavor=recursive
LDFLAGS origin=file flavor=recursive
HOME    origin=environment
PREFIX  origin=environment
NOPE    origin=undefined flavor=undefined
inside a recipe, @ has origin automatic

The classic use is telling "the user didn't set CC" apart from "CC is empty": its origin is default until someone sets it. That lets a Makefile pick a better compiler only when the user hasn't chosen one, using the ifeq from Conditionals. And when a variable has a value you can't explain, origin tells you where to look.

Where you'll use this

Here is the complete Makefile for the inventory service. Nothing in it names a source file, a module or a test:

# Every directory under src/ is a module that becomes a static library.
MODULES  := $(notdir $(patsubst %/,%,$(wildcard src/*/)))
VERSION  := $(shell git describe --tags --always --dirty 2>/dev/null || echo 0.0.0-dev)
 
CFLAGS   := -Wall -Wextra -O2
CPPFLAGS := -Iinclude -DVERSION='"$(VERSION)"'
 
LIBS     := $(foreach m,$(MODULES),lib/lib$(m).a)
TESTS    := $(patsubst tests/%.c,bin/%,$(wildcard tests/*.c))
 
.PHONY: all test clean
 
all: bin/inventory
 
bin/inventory: obj/main.o $(LIBS) | bin
	$(CC) -o $@ obj/main.o $(LIBS)
 
define MODULE_RULES
$(1)_OBJS := $$(patsubst src/%.c,obj/%.o,$$(wildcard src/$(1)/*.c))
lib/lib$(1).a: $$($(1)_OBJS) | lib
	$$(AR) rcs $$@ $$^
endef
$(foreach m,$(MODULES),$(eval $(call MODULE_RULES,$(m))))
 
obj/%.o: src/%.c
	@mkdir -p $(@D)
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
 
bin/test_%: tests/test_%.c $(LIBS) | bin
	$(CC) $(CPPFLAGS) $(CFLAGS) -o $@ $< $(LIBS)
 
test: $(TESTS)
	@$(foreach t,$(TESTS),./$(t) &&) echo "all $(words $(TESTS)) test programs passed"
 
bin lib:
	mkdir -p $@
 
print-%:
	@echo '$* = $($*)'
 
clean:
	rm -rf obj lib bin

What each function is doing:

  • wildcard + patsubst + notdir discover the modules. foreach turns them into library names.
  • shell asks Git for a version once, and -DVERSION=... bakes it into the program.
  • eval/call generate one archive rule per module. @mkdir -p $(@D) in the object rule creates nested obj/net/-style directories on demand.
  • test uses foreach inside a recipe to build the shell command ./bin/test_cache && ./bin/test_http && echo ..., so the first failing test stops the chain.
  • print-% is a pattern rule for debugging: make print-LIBS prints any variable. Nearly every large Makefile has one.
make
./bin/inventory
make
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/main.o src/main.c
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/net/http.o src/net/http.c
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/net/tls.o src/net/tls.c
mkdir -p lib
ar rcs lib/libnet.a obj/net/http.o obj/net/tls.o
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/store/cache.o src/store/cache.c
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/store/disk.o src/store/disk.c
ar rcs lib/libstore.a obj/store/cache.o obj/store/disk.o
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/util/log.o src/util/log.c
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/util/strbuf.o src/util/strbuf.c
ar rcs lib/libutil.a obj/util/log.o obj/util/strbuf.o
mkdir -p bin
cc -o bin/inventory obj/main.o lib/libnet.a lib/libstore.a lib/libutil.a
inventory befde0f
data dir:  /var/lib/inventory
min TLS:   TLSv1.2
KB-104:    42 in stock
200 ok?    yes
make: Nothing to be done for 'all'.

The tests and the debugging helper:

make test
make print-MODULES print-LIBS print-TESTS print-VERSION print-net_OBJS
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -o bin/test_cache tests/test_cache.c lib/libnet.a lib/libstore.a lib/libutil.a
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -o bin/test_http tests/test_http.c lib/libnet.a lib/libstore.a lib/libutil.a
test_cache: ok
test_http: ok
all 2 test programs passed
MODULES = net store util
LIBS = lib/libnet.a lib/libstore.a lib/libutil.a
TESTS = bin/test_cache bin/test_http
VERSION = befde0f
net_OBJS = obj/net/http.o obj/net/tls.o

print-net_OBJS works because eval created a real variable called net_OBJS. Now the payoff. A new module is just a new directory. I created src/audit/ and include/audit/, a header declaring void audit_event(const char *what);, and this source file:

#include <stdio.h>
#include "audit/audit.h"
 
void audit_event(const char *what)
{
    printf("audit: %s\n", what);
}
make
make print-MODULES print-LIBS
cc -Iinclude -DVERSION='"befde0f"' -Wall -Wextra -O2 -c -o obj/audit/audit.o src/audit/audit.c
ar rcs lib/libaudit.a obj/audit/audit.o
cc -o bin/inventory obj/main.o lib/libaudit.a lib/libnet.a lib/libstore.a lib/libutil.a
MODULES = audit net store util
LIBS = lib/libaudit.a lib/libnet.a lib/libstore.a lib/libutil.a

No Makefile edit: the module was discovered, compiled, archived and linked. Tag a release and the version follows:

git tag v1.4.0
make print-VERSION
VERSION = v1.4.0

One caution with static libraries: the linker processes them in order, and a library can only use symbols from libraries after it on the command line. Alphabetical order works here because util, which the others depend on, happens to sort last. Real projects with tangled module dependencies list LIBS in an explicit order, or use one object list instead of per-module archives.

Common mistakes

Spaces after commas

SRCS := src/main.c src/net/http.c
 
$(info [$(patsubst %.c,%.o,$(SRCS))])
$(info [$(patsubst %.c, %.o, $(SRCS))])
$(info [$(subst .c, .o,$(SRCS))])
$(info [$(addprefix obj/, main.o http.o)])
 
all: ; @:
make -f comma.mk
[src/main.o src/net/http.o]
[ src/main.o  src/net/http.o]
[src/main .o src/net/http .o]
[obj/main.o obj/http.o]

The second line has stray spaces in the result, which usually doesn't matter but breaks string comparisons. The third is a real bug: subst inserted the space literally, giving src/main .o, two words. The last one happens to be fine, because a leading space in a list of words is ignored. You don't want to remember which functions forgive you. Never put a space after a comma in a function call.

$(wildcard) can't see files the build creates

wildcard runs when the Makefile is read, before any recipe. Here, gen/version.c is generated by a rule, and the object list is built with wildcard:

OBJS := $(patsubst %.c,%.o,$(wildcard app/*.c gen/*.c))
 
report: gen/version.c $(OBJS)
	$(CC) -o $@ $(OBJS)
 
gen/version.c: VERSION
	mkdir -p gen
	echo 'const char *build_version = "$(shell cat VERSION)";' > $@
 
clean:
	rm -rf gen app/*.o report
make
make
./report
mkdir -p gen
echo 'const char *build_version = "1.4.2";' > gen/version.c
cc    -c -o app/main.o app/main.c
cc -o report app/main.o
[…]
main.c:(.text+0xb): undefined reference to `build_version'
[…]
collect2: error: ld returned 1 exit status
make: *** [Makefile:4: report] Error 1
cc    -c -o gen/version.o gen/version.c
cc -o report app/main.o gen/version.o
report tool 1.4.2

The first build fails and the second succeeds: on the first run gen/version.c didn't exist when wildcard looked. "It works if you run make twice" is the signature of this bug, and in CI, where every build is a first build, it fails every time. List generated files explicitly:

GEN_SRCS := gen/version.c
OBJS     := $(patsubst %.c,%.o,$(wildcard app/*.c) $(GEN_SRCS))
cc    -c -o app/main.o app/main.c
mkdir -p gen
echo 'const char *build_version = "1.4.2";' > gen/version.c
cc    -c -o gen/version.o gen/version.c
cc -o report app/main.o gen/version.o

(These objects were built by Make's built-in %.o: %.c rule, hence the odd spacing. I've trimmed three linker lines that show the toolchain's path.)

Single $ inside an eval template

Here is the module template with single dollar signs, as most people write it the first time:

define MODULE_RULES
$(1)_OBJS := $(patsubst src/%.c,obj/%.o,$(wildcard src/$(1)/*.c))
lib/lib$(1).a: $($(1)_OBJS)
	$(AR) rcs $@ $^
endef
make -f eval-bad.mk lib/libnet.a
ar rcs  
Usage: ar [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV] [--plugin <name>] [member-name] [count] archive-file file...
[…]
make: *** [eval-bad.mk:8: lib/libnet.a] Error 1

call expanded $@ and $^ while building the text, outside any rule, so they were empty and the recipe became ar rcs with no arguments. $($(1)_OBJS) was empty too, because net_OBJS didn't exist yet when call ran, so the library had no prerequisites. Double every $ that should be expanded later, and print the template with $(info $(call ...)) when in doubt.

Summary

  • Function calls look like $(name arg1,arg2). Arguments are expanded first. Never put spaces after commas.
  • Text: patsubst (or $(VAR:a=b)) maps lists, filter/filter-out select, sort sorts and deduplicates, words/word/firstword/lastword count and pick.
  • Files: wildcard lists what exists now, sorted, no **. dir/notdir/basename/suffix split names. abspath is textual, realpath resolves symlinks and needs the file.
  • foreach loops, call runs your own =-defined functions with $(1), $(2).
  • Empty is false and anything else is true, including 0. Test user flags with filter.
  • $(shell ...) runs while the Makefile is read; assign it with := or it runs on every reference. A failing command returns its output, not an error; see .SHELLSTATUS.
  • eval parses generated text as Makefile code. In templates, $(1) gets one $, and everything for the second pass gets $$. Debug with $(info $(call ...)).
  • info, warning and error print or stop. Inside a recipe they only fire when that target runs. origin and flavor tell you where a value came from and how it expands.

Exercises

Exercise 1: Count sources per moduleeasy

In the inventory project, print one word per module of the form name:count, where count is the number of .c files in that module's directory.

Show Solution
MODULES := $(notdir $(patsubst %/,%,$(wildcard src/*/)))
 
$(info $(foreach m,$(MODULES),$(m):$(words $(wildcard src/$(m)/*.c))))
 
all: ; @:
make -f ex1.mk
net:2 store:2 util:2

foreach evaluates its third argument once per module, and inside it wildcard and words use the current value of m.

Exercise 2: A to_obj functionmedium

Write a function to_obj that maps src/X.c to build/obj/X.o for any number of files, use it to build OBJS from every source in src/ and its subdirectories, and print both a single conversion and the full list.

Show Solution
to_obj = $(patsubst src/%.c,build/obj/%.o,$(1))
 
SRCS := $(wildcard src/*.c src/*/*.c)
OBJS := $(call to_obj,$(SRCS))
 
$(info $(call to_obj,src/net/http.c))
$(info $(OBJS))
 
all: ; @:
make -f ex2.mk
build/obj/net/http.o
build/obj/main.o build/obj/net/http.o build/obj/net/tls.o build/obj/store/cache.o build/obj/store/disk.o build/obj/util/log.o build/obj/util/strbuf.o

to_obj must use = so $(1) is filled in at call time. Because patsubst works on every word, the same function handles one file or a whole list.

Exercise 3: Validate a deploy target's inputmedium

Write a deploy target that only proceeds when DEPLOY_ENV is exactly staging or production, and otherwise stops with a message that lists the allowed values and shows what was given. Other targets in the Makefile must not be affected.

Show Solution
ENVIRONMENTS := staging production
 
.PHONY: deploy
deploy:
	$(if $(filter $(DEPLOY_ENV),$(ENVIRONMENTS)),,$(error DEPLOY_ENV must be one of: $(ENVIRONMENTS) (got '$(DEPLOY_ENV)')))
	@echo "deploying to $(DEPLOY_ENV)"
make -f ex3.mk deploy DEPLOY_ENV=prod
make -f ex3.mk deploy
make -f ex3.mk deploy DEPLOY_ENV=staging
ex3.mk:5: *** DEPLOY_ENV must be one of: staging production (got 'prod').  Stop.
ex3.mk:5: *** DEPLOY_ENV must be one of: staging production (got '').  Stop.
deploying to staging

$(filter $(DEPLOY_ENV),$(ENVIRONMENTS)) is non-empty only for an exact match, and empty when DEPLOY_ENV is unset. Because the check lives in the recipe, it only runs when deploy is built.

Exercise 4: Generate a check target per modulehard

Use define, call and eval to generate a phony check-<module> target for every module, which runs the compiler with -fsyntax-only on that module's sources and prints module <name>: OK. Add a check target that runs all of them. Then add a broken file to one module and confirm make check stops on it.

Hint

The module name should be expanded by call (one $). The compiler variable and the wildcard can be expanded either way, but writing them with $$ keeps the generated text readable and defers them to eval. addprefix builds the list for check.

Show Solution
MODULES := $(notdir $(patsubst %/,%,$(wildcard src/*/)))
 
define CHECK_RULE
.PHONY: check-$(1)
check-$(1):
	$$(CC) -Iinclude -Wall -Wextra -fsyntax-only $$(wildcard src/$(1)/*.c)
	@echo "module $(1): OK"
endef
$(foreach m,$(MODULES),$(eval $(call CHECK_RULE,$(m))))
 
.PHONY: check
check: $(addprefix check-,$(MODULES))
make -f ex4.mk check
printf 'int broken(void) { return undefined_name; }\n' > src/store/broken.c
make -f ex4.mk check
cc -Iinclude -Wall -Wextra -fsyntax-only src/net/http.c src/net/tls.c
module net: OK
cc -Iinclude -Wall -Wextra -fsyntax-only src/store/cache.c src/store/disk.c
module store: OK
cc -Iinclude -Wall -Wextra -fsyntax-only src/util/log.c src/util/strbuf.c
module util: OK
cc -Iinclude -Wall -Wextra -fsyntax-only src/net/http.c src/net/tls.c
module net: OK
cc -Iinclude -Wall -Wextra -fsyntax-only src/store/broken.c src/store/cache.c src/store/disk.c
src/store/broken.c: In function ‘broken’:
src/store/broken.c:1:27: error: ‘undefined_name’ undeclared (first use in this function)
    1 | int broken(void) { return undefined_name; }
      |                           ^~~~~~~~~~~~~~
src/store/broken.c:1:27: note: each undeclared identifier is reported only once for each function it appears in
make: *** [ex4.mk:9: check-store] Error 1

The new file was picked up automatically by the wildcard in the template. Note the error location: line 9 is the $(foreach ...) line, since that's where the generated rule came from. make check-net runs a single module's check.


Tested with: GNU Make 4.3, GCC 13.3 (with GNU ar) and Git 2.43 on Ubuntu 24.04 (WSL2), November 2026. Every Makefile and output above was run as shown. The trims are ar's long usage message and linker lines containing the toolchain's install path. The Git hashes are from a throwaway repository created for the test, so yours will differ.

Was this page helpful?
The Dark Debugger

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.