I read the Using Variables section of the GNU make documentation but couldn't understand how make variables are expanded in make rules when they are defined several times.
See, for example, the following short makefile:
.PHONY: run
run: a b
TARGET := a
$(TARGET):
echo $(TARGET)
touch $@
TARGET := b
$(TARGET):
echo $(TARGET)
touch $@
which yields the following output when running make
:
echo b
b
touch a
echo b
b
touch b
It seems that there is a target for a
, and the automatic variable $@
is indeed a
. But echoing the TARGET
variable, which is the target name as well, prints b
... What's going on here?
I'd appreciate any help, preferably with linking to the docs, that clarifies this behavior.
Other questions that are probably related:
- Is the makefile read only once when
make
is invoked? - Are the target names expanded when the makefile is read or later?
- Are the target rules expanded when the makefile is read or later?
Note: using recursively expanded variable (that is, changing :=
to =
) doesn't change the output in the above example.
a
and the name of the second isb
, 3) the recipes (the commands within the rules) are expanded only when the rules are executed, by which timeTARGET
isb
. – Beta