Makefile learning 1 - file name wildcard

I. Introduction

        The wildcards that can be used are "*", "?", "[...]", for example, *.c means all files ending with .c in the current working directory, but these wildcards in Makefile cannot be used in anywhere.

2. The use of wildcards

Wildcards in Makefile can appear in the following two situations

1. Targets and dependencies used in rules

Make will automatically match it when reading the Makefile. Examples are as follows:

# 打印当前工作目录的全部的.c文件
print: *.c
    ls $?

2. Used in the command of the rule

The wildcard processing is done when the shell executes the command. Examples are as follows:

# 删除所有的.o文件
clean:
    rm -f *.o

When wildcards in Makefile are not applicable

1. Use wildcards for variable definitions

Examples are as follows:

objects = *.o
foo : $(objects)
    cc -o foo $(CFLAGS) $(objects)

        The above objects will be a string "*.o", not a list of all ".o" files. Here if all ".o" files are deleted, the "cc -o foo $(CFLAGS) $(objects)" command will report an error.

Wildcard is needed here , and the correct usage should be objects = $(wildcard *.o) .

3. The use of wildcard function

        In rules, wildcards will be automatically expanded, but in the definition of variables and the use of functions, wildcards will be invalid. At this point, if you still want wildcards to work, you need to use the function "wildcard".

1. Usage

        $(wildcard PATTERN)

2. Effect

        It will be expanded to an existing, space-separated list of all files matching the pattern. If no file matching the pattern exists, the function ignores the pattern characters and returns null.

3. Case

The sample code is as follows:

objects := $(patsubst %.c,%.o,$(wildcard *.c))

target:$(objects)
    cc -o target $(objects)

        First use $(wildcard *.c) to get all the ".c" file names in the current working directory, then use the function patsubst to replace the ".c" file names with ".o" file names, and assign them to the objects variable. Note that cc -o target $(objects) also uses the Makefile's implicit rules.

4. Summary

        This article introduces the meaning of wildcards, and introduces two occasions where wildcards are applicable: they are used in the target and dependency of rules, and they are used in commands; when they are not applicable: the definition of variables. It also introduces the wildcard, which applies to the definition of variables, and finally illustrates its usage.

Guess you like

Origin blog.csdn.net/to_be_better_wen/article/details/130021611