makefile GNU Pattern Rules Directories in Pattern Rules


If the target pattern doesn't contain slashes, make will remove the directory part from the target it's trying to build before matching. The directory will then be put in front of the stem. When the stem is used to build the target name and prerequisites, the directory part is stripped from it, the stem is substituted in place of the % and finally the directory is put in front of the string. For example:

foo%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@

Will match lib/foobar.o, with:

  • Stem ($*): lib/bar
  • Target name ($@): lib/foobar.o
  • Prerequisites ($<, $^): lib/foobar.c

In this example, a lib/foo%.o rule would take precedence over the foo%.o rule because it matches to a shorter stem.