2016-08-23 129 views
0

用点分割字符串我有做的目标是这样我怎么可以在生成文件

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

我用像test.var1.var2

现在我想去做test.var1.var2.var3一个多水平怎样才能在makefile文件

编辑:

我想这样做的原因是因为我使用make文件部署多个应用程序,我想很多变数。以便用户可以部署如

make install.{app1}.{test}.{build_number} 
+0

听起来像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem),为什么你需要这样做? – user657267

+0

@ user657267我编辑了这个问题 – Karl

+1

看起来像一个过于复杂的'make app = app1 action = test build = 4.2.1'的方法。 – user657267

回答

4

使用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 

顺便说一句(实际上将占用大部分我的回答的),如果你事先知道的选项是,你可以去一些强大的元编程。说你要产生一些APPStest-{app}目标:

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) 

的前两行是“库”功能,将所谓的“模板”(tmpl-for)或生成列表中的每个元素的规则(rule-for)你提供作为第二个参数。我创建了一个tmpl-test,该应用程序名称为test-{app}。我定义了一个规则模板,它接受应用程序名称并为适当的test-{app}目标(这也是假的方式)设置目标特定的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. 

这听起来很复杂,它是,但如果你正确地抽象模板功能,它可以产生灵活和易于维护的构建系统。

+0

谢谢老兄,这是我所喜欢的 – Karl