如何使用patsubst Makefile进行替换



我有一个类似这样的makefile。我需要生成一个文件并将其作为abc.cpp(基本上去掉下划线后的任何内容,包括下划线

xyz:= abc_def
$(xyz):
(some commands here which generates a file)
mv file /tmp/$(patsubst _%,"",$@) 

However this does not work. In fact it doesn't ever match the underscore "_" in $@

mv file /tmp/abc.cpp is what i want

"%"通配符在patsusbst中工作?

patsubst函数不适用于您,因为它只能匹配一个模式。您想要匹配两种模式:_之前的任何模式和_之后的任何模式。$(patsubst _%,...)只将开头的单词与_匹配,而您的单词abc_def不以_开头,因此patsubst是no-op。

要使用GNU make函数来做你想做的事情,你需要玩一个技巧;类似于:

mv file /tmp/$(firstword $(subst _, ,$@))

这通过将_更改为空格将字符串拆分为多个单词,然后获取第一个单词。

如果你不回避使用辅助代码(即包括GNUmake库(,那么GNUmake表工具包肯定可以做到:

include gmtt.mk
xyz:= abc_def
$(xyz):
(some commands here which generates a file)
mv file /tmp/$(firstword $(call glob-match,$@,*_*)).cpp 

glob-match函数将字符串分割为匹配元素的条纹,其中每个glob字符(*?[...](和逐字逐句的字符串部分(在您的情况下只有_(构成一个匹配。或者简单地说,$(call glob-match,this_is_a_string,*_is_a_*)this_is_a_string拆分为列表this _is_a_ string(注意空格(。

最新更新