我想以更紧凑的方式应用以下代码:
hello1:
@echo "Hello1"
hello2:
@echo "Hello2"
hello3:
@echo "Hello3"
hello_all: hello1 hello2 hello3
是否有一种使用通配符编码hello_all
依赖关系的方法,例如你好*或其他什么?
答案 0 :(得分:0)
我认为没有一种本地方式可以做到这一点。在下面找到特定于您的用例的解决方案。但我认为它不能以通用的方式使用。
# The number list that will be used to generate the targets
NUMBERS = 1 2 3 4
# Function that will expand to a custom helloX target, with X the number given as parameter
# Note the strip that removes the spaces in the parameter
define createHelloTargets
HELLO_TARGETS += hello$(strip $(1))
hello$(strip $(1)):
@echo Hello$(strip $(1))
endef
# Generate one Hello target for each number in NUMBERS
$(foreach nb, $(NUMBERS), $(eval $(call createHelloTargets, $(nb))))
all: $(HELLO_TARGETS)
这将输出:
Hello1
Hello2
Hello3
Hello4
优点是你不必编写每个目标,只需填充NUMBERS var就可以了。这就是它。
基本上,这个Makefile将为NUMBERS中的每个数字X创建一个如下所示的目标:
helloX:
@echo HelloX
它还会将helloX
添加到HELLO_TARGETS
,这是所有现有helloX目标的列表。此列表在all
目标先决条件中进行了扩展。
答案 1 :(得分:0)
如果您的目标非常相似,请使用@ TimF的解决方案,因为它可以避免重复。如果它们不同并且无法推广,您可以通过一个小帮手来完成:
hello-add = $(eval HELLO_TARGETS += $1)$1
$(call hello-add,hello1):
@echo "Hello1"
$(call hello-add,hello2):
@echo "Hello2"
$(call hello-add,hello3):
@echo "Hello3"
hello_all: $(HELLO_TARGETS)
hello-add
接受一个参数,将其添加到HELLO_TARGETS
变量,并扩展到该参数(因为eval
扩展为空)。它表现得像:
HELLO_TARGETS += hello1
hello1:
...
但是避免必须两次写目标名称。