Makefile Functions & Text Processing

GNU make text, path, conditional, shell, and metaprogramming functions with practical examples.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Text and list functions

Manipulate words, whitespace, patterns, and filenames.

subst replace text

Replace every occurrence of one string with another.

makefileANYfunctionssubst
makefile
OUT := $(subst src/,build/,$(SRC))
Notes

Useful for path rewrites and simple string replacement.

patsubst pattern replacement

Replace words matching a `%` pattern.

makefileANYfunctionspatsubst
makefile
OBJ := $(patsubst %.c,%.o,$(SRC))
Notes

A core building block in many makefiles.

strip whitespace

Trim extra leading, trailing, and repeated internal whitespace.

makefileANYfunctionsstrip
makefile
NAME := $(strip $(NAME))
Notes

Useful before equality tests or diagnostics.

findstring substring search

Return the search string if found.

makefileANYfunctionsfindstring
makefile
HAS_TEST := $(findstring test,$(MAKECMDGOALS))
Notes

A simple way to check for word presence.

word and wordlist

Extract words by position.

makefileANYfunctionswordwordlist
makefile
FIRST := $(word 1,$(FILES))
REST := $(wordlist 2,$(words $(FILES)),$(FILES))
Notes

Handy when manipulating word lists.

firstword and lastword

Grab the first or last word of a list.

makefileANYfunctionsfirstwordlastword
makefile
CURRENT_MK := $(lastword $(MAKEFILE_LIST))
Notes

A common pattern when introspecting included makefiles.

join lists

Concatenate corresponding words from two lists.

makefileANYfunctionsjoin
makefile
PAIRS := $(join a b c,.o .d .map)
Notes

Less common, but useful for generated file lists.

addprefix and addsuffix

Add text to every word in a list.

makefileANYfunctionsaddprefixaddsuffix
makefile
BINS := $(addprefix dist/,$(TARGETS))
OBJ := $(addsuffix .o,$(NAMES))
Notes

Very common in build list generation.

dir, notdir, basename, suffix

Split and recombine filenames.

makefileANYfunctionsfilenames
makefile
DIRS := $(dir $(FILES))
BASE := $(basename $(FILES))
Notes

Useful for path manipulation without shelling out.

abspath and realpath

Normalize paths.

makefileANYfunctionspaths
makefile
ROOT := $(realpath .)
CACHE := $(abspath .cache)
Notes

`realpath` resolves symlinks when possible; `abspath` just normalizes.

Conditional and boolean-like functions

Inline branching without parser-level `ifeq`.

if function

Select one of two expansions based on non-empty condition text.

makefileANYfunctionsif
makefile
MODE_MSG := $(if $(CI),ci-mode,local-mode)
Notes

Good when you need expression-like branching inside variables.

or function

Return the first non-empty argument.

makefileANYfunctionsor
makefile
PORT := $(or $(APP_PORT),3000)
Notes

Useful for defaults and override chains.

and function

Return the last argument if all are non-empty.

makefileANYfunctionsand
makefile
READY := $(and $(DB_URL),$(API_KEY),yes)
Notes

Handy for gating optional behavior.

intcmp function

Compare integers in GNU make 4.4+.

makefileANYfunctionsintcmpgnu-make
makefile
RESULT := $(intcmp $(JOBS),8,lt,eq,gt)
Notes

Useful when you need numeric branching purely inside make.

Shell, call, eval, and generated rules

The metaprogramming toolbox for large makefiles.

shell function

Capture shell command output at parse time.

makefileANYfunctionsshell
makefile
GIT_SHA := $(shell git rev-parse --short HEAD)
Notes

Use sparingly; every call runs during parsing.

call macro with arguments

Invoke a user-defined macro like a function.

makefileANYfunctionscallmacros
makefile
define banner
$(info === $(1) ===)
endef

$(call banner,Deploying API)
Notes

`$(1)`, `$(2)`, and so on are positional arguments inside `define` blocks and recursive vars.

eval generated rules

Generate new rules dynamically.

makefileANYfunctionsevalmetaprogramming
makefile
define make-test-target
.PHONY: test-$(1)
test-$(1):
  pytest -q tests/$(1)
endef

$(foreach p,unit integration e2e,$(eval $(call make-test-target,$(p))))
Notes

`eval` lets make parse generated text as makefile syntax.

value raw variable text

Read a variable without expanding it.

makefileANYfunctionsvalue
makefile
RAW_RULE := $(value SOME_TEMPLATE)
Notes

Useful when working with `eval` and templates.

file function

Write content to a file from make.

makefileANYfunctionsfileoutput
makefile
$(file >build/version.txt,$(VERSION))
Notes

GNU make can create or append files during parsing or expansion.

warning and error functions

Emit diagnostics or abort parsing.

makefileANYfunctionswarningerror
makefile
$(warning building with DEBUG=$(DEBUG))
$(if $(DB_URL),,$(error DB_URL is required))
Notes

Great for fail-fast validation of required inputs.

info tracing

Print information during parsing.

makefileANYfunctionsinfodebug
makefile
$(info Sources: $(SRC))
Notes

Helpful when debugging generated variables and includes.

Useful function recipes

Practical patterns built from core functions.

Self-documenting help target

Extract target comments from the current makefile.

makefileANYhelprecipesawk
makefile
.PHONY: help
help:
  @grep -E '^[a-zA-Z0-9_.-]+:.*?## ' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "%-24s %s
", $$1, $$2}'
Notes

Popular pattern for `make help`.

Use MAKECMDGOALS

Inspect requested goals.

makefileANYspecial-variablesgoals
makefile
$(info goals=$(MAKECMDGOALS))
Notes

`MAKECMDGOALS` contains explicit command-line goals.

Current makefile name

Get the most recently parsed makefile path.

makefileANYspecial-variablesmakefile-list
makefile
CURRENT_MK := $(lastword $(MAKEFILE_LIST))
Notes

A practical use of `MAKEFILE_LIST`.

Define whitespace helpers

Create reusable space or comma variables.

makefileANYrecipestext
makefile
empty :=
space := $(empty) $(empty)
comma := ,
Notes

Useful in advanced text generation scenarios.

Recommended next

No recommendations yet.