>_ IzzyLab

Hands-on task

This task is step 9 of the course “Make: builds and automation”

Pattern rule and automatic variables

medium~7 min

In /root/proj there are a.c and b.c. Write a Makefile that "builds" a same-named .o from each .c (in practice — copies the contents). Don't write two separate rules: use one pattern rule %.o: %.c with automatic variables ($< — the source, $@ — the target). Add a default target all: a.o b.o so that bare make builds both. The Makefile is handy to write in the Editor tab above the terminal: in a Makefile it puts a real TAB at the start of a recipe line.

What you'll practise:
  • make
  • pattern rules
  • automatic variables
  • default target

Topic breakdown

The pattern rule %.o: %.c describes a whole class of targets with a single entry: the % sign is the "stem" of the name, identical for the target and the dependency. So the recipe doesn't depend on specific names, it uses automatic variables: $< fills in the first dependency (the source), $@ the name of the target being built. The first target in the file becomes the default target, so a separate all depending on the required .o files defines exactly what bare make will build.

What's checked

  1. make builds a.o and b.o from the pattern
  2. one pattern rule works for any .c

What it looks like