在GNU中Makefile,有两种类型的变量:
# simple variable (immediate evaluation):
VAR := some_assignment
# recursively expanded variable (deferred evaluation):
VAR = some_assignment
Run Code Online (Sandbox Code Playgroud)
可以使用以下方法将其追加到递归扩展的变量中:
IMMEDIATE += DEFERRED or IMMEDIATE
Run Code Online (Sandbox Code Playgroud)
对于追加运算符'+ =',如果先前已将该变量设置为简单变量(':='或':: ='),则认为右侧是立即数,否则推迟。
有没有什么办法来预先考虑到递归扩展变量?
我的激励示例是在以下方面引入一个新的库$(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)
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题。我的解决方案很笨拙,并且使用$(value)和$(eval)函数。
对我来说重要的是,它保留了变量的风格(递归),因此在执行此操作时,既不会扩展前置变量,也不会扩展原始变量:
# 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
Run Code Online (Sandbox Code Playgroud)
快速测试用例:
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))
Run Code Online (Sandbox Code Playgroud)
及其执行:
before: VAR=A | value(VAR)=$(A) | recursive
after : VAR=BA | value(VAR)=$(B)$(A) | recursive
make: *** No targets. Stop.
Run Code Online (Sandbox Code Playgroud)
附加条款:
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |