在 GNU Makefile
中,有两种类型的变量:
# simple variable (immediate evaluation):
VAR := some_assignment
# recursively expanded variable (deferred evaluation):
VAR = some_assignment
可以使用以下方法附加到递归扩展的变量:
IMMEDIATE += DEFERRED or IMMEDIATE
有没有办法将 预先添加到递归扩展的变量中?
我的激励示例是在
$(LDLIBS)
中的其他库之前引入一个新库: # Unfortunately, newlib gets added to the end rather than the beginning.
LDLIBS += $(if $(later_condition),newlib.a)
# Unfortunately, the expression is evaluated now rather than being deferred.
LDLIBS := $(if $(later_condition),newlib.a) $(LDLIBS)
最佳答案
我遇到了同样的问题。我的解决方案非常笨拙,并使用了 $(value) 和 $(eval) 函数。
对我来说重要的是 它保留了变量 的 flavor (递归),因此在此操作期间既不会扩展前置变量,也不会扩展原始变量:
# Macro for prepending to a recursively expanded variable.
#
# Usage:
# * Prepending "text" to the VAR variable:
# $(call prepend,VAR,text)
#
# * Prepending "a word list" to the VAR variable -- remember
# to add any trailing separator character (e.g. space):
# $(call prepend,VAR,a word list )
#
# * Prepending OTHER_VAR variable to the VAR variable -- use $$
# to defer any variable expansions:
# $(call prepend,VAR,$$(OTHER_VAR))
define prepend
$(eval $(1) = $(2)$(value $(1)))
endef
# Macro for appending to a recursively expanded variable.
#
# Usage:
# * Appending "text" to the VAR variable:
# $(call append,VAR,text)
#
# * Appending "a word list" to the VAR variable -- remember
# to add any heading separator character (e.g. space):
# $(call append,VAR, a word list)
#
# * Appending OTHER_VAR variable to the VAR variable -- use $$
# to defer any variable expansions:
# $(call append,VAR,$$(OTHER_VAR))
define append
$(eval $(1) = $(value $(1))$(2))
endef
快速测试用例:
A = A
B = B
VAR = $(A)
$(info before: VAR=$(VAR) | value(VAR)=$(value VAR) | $(flavor VAR))
$(call prepend,VAR,$$(B))
$(info after : VAR=$(VAR) | value(VAR)=$(value VAR) | $(flavor VAR))
及其执行:
before: VAR=A | value(VAR)=$(A) | recursive
after : VAR=BA | value(VAR)=$(B)$(A) | recursive
make: *** No targets. Stop.
补充笔记:
关于makefile - GNU 制作 : prepend a recursively expanded variable?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35516996/