Makefile by Example: Wildcards
Wildcards allow you to select files based on patterns. This example shows how to use `*` and the `wildcard` function.
Code
# Simple wildcard in a rule
clean:
rm -f *.o
# The wildcard function expands immediately
# SRCS will contain a list: main.c utils.c foo.c ...
SRCS := $(wildcard *.c)
# Substitution reference to create object list
# Replaces .c with .o for every word in SRCS
OBJS := $(SRCS:.c=.o)
app: $(OBJS)
$(CC) -o $@ $^
# Debug print
info:
@echo "Source files: $(SRCS)"
@echo "Object files: $(OBJS)"Explanation
Make supports wildcards similar to the shell. The character * matches any sequence of characters. You can use this in recipes (commands), where it is expanded by the shell (e.g., rm *.o). However, if you use * in a variable definition like FILES = *.c, it is NOT expanded immediately; it remains the string "*.c".
To expand wildcards in variable definitions, you must use the wildcard function: $(wildcard *.c). This searches the filesystem and returns a space-separated list of matching files. This is extremely useful for automatically discovering source files so you don't have to list them manually.
Once you have a list of source files, you often need a corresponding list of object files. You can use a substitution reference $(VAR:suffix=replacement) to transform the list. $(SRCS:.c=.o) takes the list of source files and replaces the .c extension with .o for each one.
Code Breakdown
$(wildcard *.c) is a function call. It returns the list of existing C files in the directory.$(SRCS:.c=.o) is a substitution reference. It's a shorthand for the patsubst function.
