gpt4 book ai didi

makefile - 我如何在makefile中用点分割字符串

转载 作者:行者123 更新时间:2023-12-04 22:43:11 25 4
gpt4 key购买 nike

我有这样的目标

test.%
export var1=$(basename $*) && export var2=$(subst .,,$(suffix $*))

我使用类似 test.var1.var2
现在我想再做一个级别,如 test.var1.var2.var3我怎样才能在 makefile 中得到它

编辑:

我想这样做的原因是因为我使用 Make 文件来部署多个应用程序并且我想要很多变量。以便用户可以像这样部署
make install.{app1}.{test}.{build_number}

最佳答案

使用 subst用空格替换点,使其成为一个列表。然后使用 word访问特定元素:

word-dot = $(word $2,$(subst ., ,$1))

test.%:
export var1=$(call word-dot,$*,1) && export var2=$(call word-dot,$*,2) && export var3=$(call word-dot,$*,3)

哪些输出:
$ make test.foo.bar.baz
export var1=foo && export var2=bar && export var3=baz

顺便说一句(这实际上会占用我的大部分答案),如果您事先知道选项是什么,您可以使用一些强大的元编程。假设您要生成 test-{app}一些目标 APPS :
tmpl-for = $(foreach x,$2,$(call $1,$x))
rule-for = $(foreach x,$2,$(eval $(call $1,$x)))

APPS := foo bar baz

tmpl-test = test-$1

define test-vars-rule
$(call tmpl-test,$1): APP := $1
.PHONY: $(call tmpl-test,$1)
endef

$(call rule-for,test-vars-rule,$(APPS))
$(call tmpl-for,tmpl-test,$(APPS)):
@echo Testing app: $(APP)

前两行是“库”函数,它们将为您作为第二个参数提供的列表中的每个元素调用"template"( tmpl-for )或生成规则( rule-for )。我创建了一个 tmpl-test它采用应用程序名称并给出 test-{app} .我定义了一个规则模板,它采用应用程序名称并设置特定于目标的 APP适当的变量 test-{app}目标(顺便说一句,这也是假的)。然后我使用 rule-for创建我的所有设置规则 APP .最后,我写出目标的实际主体,并使用 tmpl-for 获得所有可能目标的列表。 .
$ make test-foo
Testing app: foo
$ make test-bar
Testing app: bar
$ make test-baz
Testing app: baz
$ make test-blah
make: *** No rule to make target 'test-blah'. Stop.

这听起来很复杂,确实如此,但是如果您正确地抽象模板函数,它可以生成灵活且易于维护的构建系统。

关于makefile - 我如何在makefile中用点分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39092055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com