Makefile by Example: Rules
Implicit rules are built-in rules that Make knows. This sample shows how to leverage and override them.
Code
# Make knows how to build .o from .c automatically!
# We don't need to write the rule explicitly.
CC = clang
CFLAGS = -O3
# Just listing the target and dependencies is enough
# Make uses its implicit rule: $(CC) $(CPPFLAGS) $(CFLAGS) -c
main.o: main.c
utils.o: utils.c
app: main.o utils.o
$(CC) $(LDFLAGS) -o $@ $^
# We can also define our own suffix rules (old style)
.SUFFIXES: .java .class
.java.class:
javac $<Explanation
GNU Make comes with a large database of built-in rules, called implicit rules. For example, it already knows that to create a .o file from a .c file, it should run $(CC) -c $(CFLAGS) $(CPPFLAGS). You don't need to write this rule yourself; you just need to define the variables CC and CFLAGS.
You can see the database of implicit rules by running make -p. Leveraging these rules makes your Makefile much shorter and more standard. You simply list the dependencies (e.g., main.o: main.c), and Make fills in the recipe.
While pattern rules (%.o: %.c) are the modern way to define generic build steps, older Makefiles used "suffix rules" like .c.o:. Suffix rules are still supported for backward compatibility but are less flexible than pattern rules.
Code Breakdown
CC = clang overrides the default compiler (usually cc or gcc) used by the implicit rules..SUFFIXES is used to introduce new file extensions for suffix rules.
