makefile 字符串处理函数

时间:2023-03-09 00:45:31
makefile  字符串处理函数

截取自《跟我一起写Makefile》

(1)  $(subst <from>, <to>, <text>)

名称: 字符串替换函数 subst

功能: 把字符串<text>中的<from>字符串替换成<to>

返回: 被替换后的字符串

eg:    $(subst ee, EE, feet on the street)

把"feet on the street" 中的"ee" 替换成 "EE",返回的结果为 "fEEt on the street"

(2)  $(pathsubst <pattern>, <replacement>, <text>)

名称: 模式字符串替换函数 pathsubst

功能: 查找<text>中的单词(单词以“空格”、“TAB”、“回车”、“换行”分隔)是否符合模式<pattern>,如果匹配的话,则以<replacement>替换。这里,<pattern>可以包括通配符“%”,表示任意长度的字串。如果<replacement>中也包含“%”,那么,<replacement>中的这个“%”将时<pattern>中的那个“%”所代表的字串。(可以用"\"来转义,以"\%"来表示真实含义的"%"字符)。

返回:被替换后的字符串

eg:    $(pathsubst %.c, %.o, x.c.c bar.c)

把字符串“x.c.c bar.c”符合模式[%.c]的单词替换成[%.o], 返回结果为"x.c.o bar.o"

(3)$(strip <string>)

名称: 去空格函数  strip

功能: 去掉<string> 字符串中开头和结尾的空字符

返回: 去掉空格后的字符串

eg:   $(strip  a b c )

把字符串“a b c  ”去掉开头和结尾的空格,结果是"a b c"

(4) $(findstring <find>, <in>)

名称:  查找字符串函数 findstring

功能: 在字符串<in>中查找<find>字串

返回: 如果找到,那么返回<find>, 否则返回空字符串

eg:  $(findstring a,  a b c)    返回字符串"a"

$(findstring a,  b c)      返回字符串""(空字符串)

(5)$(filter <pattern...>, <text>)

名称: 过滤函数 filter

功能: 以<pattern>模式过滤<text>字符串中的单词,保留符合模式<pattern>的单词,可以有多个模式

返回: 符合模式<pattern>的字串

eg:  sources := foo.c  bar.c  baz.s  ugh.h

foo:  $(sources)

cc $(filter %.c %.s,  $(sources)) -o foo

$(filter %.c %.s,  $(sources))的返回值为"foo.c bar.c baz.s"

(6)$(filter-out <pattern...>, <text>)

名称: 反过滤函数 filter-out

功能: 以<pattern>模式过滤<text>字符串中的单词,去除符合<pattern>模式的单词,可以有多个模式

返回: 不符合模式<pattern>的字符串

eg:    objects =  main1.o  foo.o  main2.o bar.o

mains = main1.o  main2.o

$(filter-out $(mains), $(objects)) 返回值是 "foo.o  bar.o"

(7)$(sort <list>)

名称: 排序函数  sort

功能: 给字符串<list>中的单词排序(升序)

返回: 排序后的字符串

eg:    $(sort  foo bar lose) 返回  "bar foo lose"

备注: sort函数会去掉<list>中相同的单词

(8) $(word <n>, <text>)

名称: 去单词函数  word

功能: 取字符串<text>中第<n>个单词(从1开始)

返回: 字符串<text>中的第<n>个单词,如果n大于字符串中单词数,那么返回空字符串

eg:    $(word 2,  foo  bar baz)  返回“bar”

(9)$(worelist <s>, <e>, <text>)

名称: 取单词串函数 wordlist

功能: 从字符串 <text>中取从<s>开始到<e>的单词串。<s>和<e>是一个数字。

返回: 字符串<text>中从<s>开始到<e>的单词字串。如果<s>比<text>中的单词数要大,那么返回空字符串。如果<e>大于<text>中的单词数,那么返回从<s>开始,到结尾的字符串

eg:  $(wordlist 2 , 3,  foo bar baz)  返回值为 "bar baz"

(10) $(words <text>)

名称: 单词个数统计 words

功能: 统计<text>字符串中单词个数

返回: <text>中的单词个数

eg:   $(words ,foo bar baz)  返回值是3

(11)$(firstword <text>)

名称: 首单词函数  firstword

功能: 取字符串<text>中的第一个单词

返回: 字符串<text>中的第一个单词

eg:  $(fristword  foo bar) 返回值是 "foo”

备注:  等价于  $(word  1,  <text>)

以上,是所有的字符串操作函数,如果搭配混合使用,可以完成比较复杂的功能。这里,举一个现实中应用的例子。我们知道,make使用“VPATH”变量来指定“依赖文件”的搜索路径。于是,我们可以利用这个搜索路径来指定编译器对头文件的搜索路径参数CFLAGS,如:

override CFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))

如果我们的“$(VPATH)”值是“src:../headers”,那么“$(patsubst %,-I%,$(subst :, ,$(VPATH)))”将返回“-Isrc -I../headers”,这正是cc或gcc搜索头文件路径的参数。