Static Pattern
Static patterns make it easier to define multi-target rules, allowing our rules to be more flexible and adaptable. Let’s first take a look at the syntax:
<targets …>: <target-pattern>: <prereq-patterns …> <commands>…
objects = foo.o bar.o
all: $(objects)
$(objects): %.o: %.c
$(CC) -c $(CFLAGS) $< -o $@
$<
” and “$@
” are automatic variables, where “$<
” represents the first prerequisite file (i.e., “foo.c bar.c”) and “$@
” represents the target set (i.e., “foo.o bar.o”). Thus, the rules above expand to the equivalent rules below:foo.o : foo.c
$(CC) -c $(CFLAGS) foo.c -o foo.o
bar.o : bar.c
$(CC) -c $(CFLAGS) bar.c -o bar.o
Imagine if we have hundreds of “%.o” files, we can just use this simple “static pattern rule” to write a bunch of rules, which is incredibly efficient. The usage of “static pattern rules” is very flexible, and if used well, it can be a very powerful feature.
.c.o:
gcc -c -o $*.o $
.c.o:
This line means %.o : %.c
In other words, all .o files depend on their corresponding .c files.
For example, if there are three a.c b.c c.c
Then there will be a.o b.o c.o
a.o : a.c
b.o : b.c
c.o : c.c
This is a shorthand method for makefile dependencies. There are many ways to write makefile dependencies. This is one of them.