GNU make manual 翻译(八十六)
继续翻译
4.4.3 The Function `wildcard' ----------------------------- Wildcard expansion happens automatically in rules. But wildcard expansion does not normally take place when a variable is set, or inside the arguments of a function. If you want to do wildcard expansion in such places, you need to use the `wildcard' function, like this: $(wildcard PATTERN...) This string, used anywhere in a makefile, is replaced by a space-separated list of names of existing files that match one of the given file name patterns. If no existing file name matches a pattern,then that pattern is omitted from the output of the `wildcard' function. Note that this is different from how unmatched wildcards behave in rules, where they are used verbatim rather than ignored (*note Wildcard Pitfall::). One use of the `wildcard' function is to get a list of all the C source files in a directory, like this: $(wildcard *.c) We can change the list of C source files into a list of object files by replacing the `.c' suffix with `.o' in the result, like this: $(patsubst %.c,%.o,$(wildcard *.c)) (Here we have used another function, `patsubst'. *Note Functions for String Substitution and Analysis: Text Functions.) Thus, a makefile to compile all C source files in the directory and then link them together could be written as follows: objects := $(patsubst %.c,%.o,$(wildcard *.c)) foo : $(objects) cc -o foo $(objects) (This takes advantage of the implicit rule for compiling C programs, so there is no need to write explicit rules for compiling the files. *Note The Two Flavors of Variables: Flavors, for an explanation of `:=', which is a variant of `='.)
4.4.3 wildcard 函数
-----------------------------
通配符扩展自动地在规则中发生。但是通配符扩展在变量被设置的时候,不会正常发生,通配符在函数的参数中时,扩展也不会发生。如果你想在此种场合下执行 通配符扩展,你需要使用 wildcard 函数,像下面这样:
$(wildcard PATTERN...)
以上的函数字符串,可以用在makefile的任何一个地方,将会被替换成为 用空格分隔的已存在文件的名称列表,只要它符合某种名称模式。如果没有可以匹配模式的文件,那么此模式被省略。请注意这个和 直接在规则里使用通配符时找不到匹配是的行为不同,那时将会不是被忽略,而是留下一字不差地保留下来。(*note Wildcard Pitfall::)
有一个对 wildcard 函数的用法就是,获得一个 某目录下所有C 源程序的名字列表
如下:
$(wildcard *.c)
我们可以改变 C 源程序文件的列表,使其转化为目标文件的列表,这要通过把 .c的后缀换成 .o 后缀来实现,像如下:
$(patsubst %.c,%.o,$(wildcard *.c))
(这里我们用到了另一个函数, `patsubst'. *Note Functions for
String Substitution and Analysis: Text Functions.)
因此,我们可以用一个 makefile来编译一个目录下的所有的 C 源程序,并把它们链接起来,像如下:
objects := $(patsubst %.c,%.o,$(wildcard *.c))
foo : $(objects)
cc -o foo $(objects)
(这种做法,获得了隐式规则编译C 程序的好处, 因此此处也就不需要写编译文件的显式规则了。
*Note The Two Flavors of Variables: Flavors, for an explanation of
`:=', which is a variant of `='.)
后文待续