makefile中subst和patsubst的区别
一,简介
在 Makefile 中,subst 和 patsubst 都是用于字符串替换的函数,但它们之间有一些区别:
1.1 subst 函数:
- 语法:$(subst find,replace,text)
- 功能:将字符串 text 中所有出现的 find 替换为 replace。
- 注意:subst 函数是简单的文本替换,不支持模式匹配,只会替换找到的精确字符串。
1.2 patsubst 函数:
- 语法:$(patsubst pattern,replacement,text)
- 功能:将字符串 text 中与模式 pattern 匹配的部分替换为 replacement。
- 注意:patsubst 函数支持模式匹配,模式中可以包含 % 通配符,可以匹配任意字符序列。这使得 patsubst
更加灵活,可以替换不确定的部分。
二,举例说明
例如,假设有以下 Makefile:
# 使用 subst 函数
VAR1 := foo bar baz
RESULT1 := $(subst bar,hello,$(VAR1))
# 输出:foo hello baz
# 使用 patsubst 函数
VAR2 := src/foo.c src/bar.c src/baz.c
RESULT2 := $(patsubst src/%.c,obj/%.o,$(VAR2))
# 输出:obj/foo.o obj/bar.o obj/baz.o
在上面的示例中,subst 函数将 VAR1 中的 bar 替换为 hello,而 patsubst 函数则使用模式匹配将 VAR2 中的 .c 文件路径替换为 .o 文件路径。