一篇出自 China Unix Net的《跟我一起写Makefile》，被转载了无数次。。。无奈。。。。
Searches string for matches of regexp, and substitutes replacement for each match. The syntax for regular expressions is the same as in GNU Emacs (see Regexp).
The parts of string that are not covered by any match of regexp are copied to the expansion. Whenever a match is found, the search proceeds from the end of the match, so a character from string will never be substituted twice. If regexp matches a string of zero length, the start position for the search is incremented, to avoid infinite loops.
When a replacement is to be made, replacement is inserted into the expansion, with ‘n’ substituted by the text matched by the nth parenthesized sub-expression of patsubst, for up to nine sub-expressions. The escape ‘&’ is replaced by the text of the entire regular expression matched. For all other characters, ‘’ treats the next character literally. A warning is issued if there were fewer sub-expressions than the ‘n’ requested, or if there is a trailing ‘’.
The replacement argument can be omitted, in which case the text matched by regexp is deleted.
patsubstis recognized only with parameters.
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:
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 (see section Pitfalls of Using Wildcards).
One use of the
wildcard function is to get a list of all the C source files in a directory, like this:
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. See section Functions for String Substitution and Analysis.)
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. See section The Two Flavors of Variables, for an explanation of `:=’, which is a variant of `=’.)
本作品《Linux Makefile实用教程》由verynix创作，采用知识共享署名-非商业性使用-禁止演绎 3.0 Unported许可协议进行许可。
Permissions beyond the scope of this license may be available at verynix.com.
Post Footer automatically generated by wp-posturl plugin for wordpress.