If you're in the same file, you should avoid this altogether -- stop thinking of make
as some "advanced scripting tool". It is not. It's a tool for building files doing the minimum necessary work while respecting all dependencies and therefore, your job is to exactly state these dependencies using prerequisites.
Look at this example and what it does:
var = 11
printvar:
echo $(var)
setvar:
$(eval var=22)
a: printvar setvar b
b:
echo $(var)
.PHONY: a b printvar setvar
Note that none of these rules create an actual file. Normally, a rule should create its target, if it isn't, it must be listed as a prerequisite of the special target .PHONY
to let make know this. This should be an exception -- the primary use of make
is that it can decide whether it has to apply a rule by comparing the timestamps of the prerequisites with that of the target. A rule's recipe is only executed if there's a prerequisite that is newer than the target. With a .PHONY
rule, the recipe has to be executed each and every time.
When talking about recursive make
, the question would make some more sense. One easy way to pass a variable from a parent make
process to a child is to export it to the environment. In your example, the following would do:
var ?= 11 # only set var if it doesn't have a value yet
export var # export var to the environment, so it's available to child make
a:
echo $(var)
$(eval var=22)
echo $(var)
$(MAKE) b
b:
echo $(var)
.PHONY: a b
Of course, this only makes sense in practice when you have different Makefiles, so not just call $(MAKE) b
, but e.g. $(MAKE) -C [some subdir] b
. IMHO, recursive make should be avoided as it's very hard to get the dependencies correct with recursive make. But anyways, this would work.