> 文章列表 > Makefile 中使用通配符 *

Makefile 中使用通配符 *

Makefile 中使用通配符 *

通配符 * 用于匹配文件名,可用于规则中的目标、依赖文件或者 wildcard 函数中。
建议任何时候都应该将通配符 * 放置在 wildcard 函数中使用以避免不必要的错误。
参考下面的 Makefile:

print: *.cls -la $?

执行此 Makefile 的时候,make 会查找当前目录下所有的 .c 文件,并打印出其文件信息。
但是,如果 make 没有匹配到符合表达式 *.c 的文件,那么该依赖文件表示一个名为 *.c 的文件,而当前目录下又不存在该文件,因此 make 会报以下错误:

make: *** No rule to make target `*.c', needed by `print'.  Stop.

修改上面的 Makefile 如下所示:

print: $(wildcard *.c)ls -la $?

这里使用了 wildcard 函数,在当前目录中存在 .c 文件时,make 的结果和上面是一样的。若当前目录不存在 .c 文件,那么将执行:

ls -la

此外,不建议在变量对象中直接使用通配符,而应该将其放在 wildcard 函数中使用。
参考下面 Makefile:

thing_wrong := *.o
thing_right := $(wildcard *.o)all: one two three one: $(thing_wrong)two: $(thing_right)three: $(wildcard *.o)

如果当前目录不存在 .o 文件,那么 thing_wrong 指代名为 *.o 的文件,但该文件并不存在,因此 make 会报以下错误:

make: *** No rule to make target `*.o', needed by `one'.  Stop.

twothree 的依赖文件列表在没有匹配到 .o 文件时,等价于没有依赖文件列表,因而可以顺利执行。