The process of writing a Makefile is as follows:
- Define variables: Define variables such as compiler and compilation options.
- Define target file: Define the target file name.
- Define source files: Define all source files.
- Define rules: Define the rules for compiling each source file into an object file.
- Define pseudo-target: Defines a pseudo-target that cleans up object files and other intermediate files.
CC = gcc
CFLAGS = -Wall -Wextra -Werror
SOURCES := $(wildcard *.c)
TARGETS := $(patsubst %.c, %, $(SOURCES))
all: $(TARGETS)
%: %.c
$(CC) $(CFLAGS) $< -o $@
.PHONY: clean
clean:
rm -f $(TARGETS)
CC
Defines the compiler used, gcc is used here.CFLAGS
Compilation options are defined, and some warning options are enabled here.SOURCES
is a list of all source files, using the wildcard*.c
to find all files ending with in the current directory..c
TARGETS
is a list of all executable files, using the patsubst function to replace source file paths with executable file paths (with file extensions removed).all: $(TARGETS)
Indicates that all depends on all executable files, and all executable files can be generated by typing in the command line.$ make
%: %.c
Indicates a rule,.c
compiles a file into a corresponding executable file, and stores it in a file with the same name as the source file..PHONY: clean
Indicates that clean is a pseudo-target, not a real file, and$ make clean
all executable files can be deleted by typing in the command line.