Makefile Static Pattern Rules

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>…

If our <target-pattern> is defined as “%.o”, it means that all targets in our <target> set end with “.o”. If our <prereq-patterns> is defined as “%.c”, it means that we are redefining the target set formed by <target-pattern>. The calculation method is to take the “%” in the <target-pattern> (which means removing the [.o] suffix) and adding the [.c] suffix to form a new set. Therefore, both our “target pattern” and “dependency pattern” should contain the character “%”.Don’t worry if you don’t understand, see the example below:
objects = foo.o bar.o
all: $(objects)
$(objects): %.o: %.c
	$(CC) -c $(CFLAGS) $< -o $@
In the example above, it specifies that our targets are obtained from $objects, “%.o” indicates all targets ending with “.o”, which are “foo.o bar.o”, the pattern of the variable $object set, while the dependency pattern “%.c” takes the “%” from the pattern “%.o”, which is “foo bar”, and adds the “.c” suffix, so our dependency targets are “foo.c bar.c”. The commands “$<” 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.

Example:

.c.o:

gcc -c -o $*.o $

Explanation:

.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.

Leave a Comment