Shell commands sometimes take a long time to run, so you may not want to do VAR = $(shell slow-cmd)
(with =
, the slow-cmd will be run every time the variable is referenced). Using VAR := $(shell slow-cmd)
can be useful, but if you are building a target that does not ever need the variable expanded, you will get one more invocation of the slow-cmd
than is needed. In the following makefile (with gnu-make), you can get the desired behavior: the shell command to define a value for V2 is never invoked more than once, and for the target foo
it is not invoked at all. But this is a heinous kludge. Is there a more reasonable way to ensure that a variable is only defined when needed, but never evaluated more than once?
V1 = $(shell echo evaluating V1 > /dev/tty; echo V1 VALUE)
all: foo bar V2
@echo $(V1) $@
@echo $(V2) $@
foo:
@echo $(V1) $@
bar: V2
@echo $(V1) $@
@echo $(V2) $@
V2:
$(eval V2 := $(shell echo evaluating V2 > /dev/tty; echo V2 VALUE))
.PHONY: all foo bar
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…