1
votes

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:

  1. Is the makefile read only once when make is invoked?
  2. Are the target names expanded when the makefile is read or later?
  3. 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.

1
I don't have a doc reference to back this up, but I think 1) yes, 2) the names are expanded as Make reads the file, so the name of the first rule is a and the name of the second is b, 3) the recipes (the commands within the rules) are expanded only when the rules are executed, by which time TARGET is b.Beta
@Beta that's entirely correct, I guess you should make it an answer.user2371524

1 Answers

4
votes

The information you're looking for is found in the GNU make manual section How make Reads a Makefile.