Skip to content
shellhacks.dev
Command Line

Override Makefile Variables from the Command Line

A make variable set on the command line beats the Makefile, while one from the environment loses to a plain assignment and wins over ?=. The -e option reverses that.

1 min read
Summarize in AI

A Makefile sets CC = gcc, and you need to build with clang for one run.

Shell
cat > Makefile <<'EOF'
CC = gcc
OUT ?= app
show:
	@echo "CC=$(CC) OUT=$(OUT)"
EOF
make show
make show CC=clang OUT=tool
CC=clang OUT=tool make show
CC=clang OUT=tool make -e show
Text
CC=gcc OUT=app
CC=clang OUT=tool
CC=gcc OUT=tool
CC=clang OUT=tool

Arguments after the target, as in make show CC=clang, override the assignment inside the Makefile. An environment variable does not: CC=clang make show printed CC=gcc, because CC = gcc is a plain assignment that replaces the environment value. The ?= form assigns only when the variable is not set yet, so OUT=tool from the environment was used. make -e makes the environment win over plain assignments. See Overriding Variables in the make manual.

Variables passed on the command line are also passed to sub-makes and the recipes' environment, which is usually what you want and sometimes a surprise. Using -e makes a build depend on everything in the shell, which is why it is rarely recommended. Use ?= for settings that callers are meant to change. This was run with GNU Make 4.3.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.