Skip to content
systemcoding.dev
Toolchains

Print any Makefile variable with a print-% pattern rule

Add a print-% pattern rule to a GNU Makefile so make print-CFLAGS shows the final value of any variable, after all includes and overrides.

1 min read
Summarize in AI

Debugging a Makefile usually starts with "what is CFLAGS really?". Sprinkling $(info) lines and deleting them afterwards is slow. One pattern rule lets you ask about any variable from the command line.

Makefilemakefile
CC     := gcc
CFLAGS := -O2 -Wall
CFLAGS += -DVERSION=\"1.4\"

print-%:
	@echo '$* = $($*)'
Shell
make print-CC
make print-CFLAGS
make print-LDLIBS
Text
CC = gcc
CFLAGS = -O2 -Wall -DVERSION=\"1.4\"
LDLIBS = 

$* is the part of the target name that matched the %, so for print-CFLAGS it is CFLAGS. The inner $($*) expands to the variable of that name. It shows the value after the whole Makefile has been read, including included files and command-line overrides, which is exactly what the recipes see.

An empty line, as for LDLIBS here, means the variable is empty or never set. To tell those two apart, print the origin as well: @echo '$* ($(origin $*)) = $($*)' shows undefined, file, environment or command line, which settles the common question of whether the shell environment or the Makefile won.

A pattern rule with no prerequisites is always run, but it is not a phony target, so a file named print-CC would make it skip. That is rare enough to ignore. Use it by hand, not in a build. Pattern rules are described in the GNU make manual.

Taggedmake
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.