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.
The following is an example Makefile, assuming that each directory has a .c
source file ending with that needs to be compiled into the corresponding executable file:
CC = gcc
CFLAGS = -Wall -Wextra -Werror
SRCDIRS = src1 src2 src3
TARGETS := $(patsubst %, %/target, $(SRCDIRS))
all: $(TARGETS)
%/target: %/*.c
$(CC) $(CFLAGS) $^ -o $@
.PHONY: clean
clean:
find . -name target -type f -delete
CC
Defines the compiler used, gcc is used here.CFLAGS
Compilation options are defined, and some warning options are enabled here.SRCDIRS
Defines the directory where all source files reside.TARGETS
is a list of all executable files, using the patsubst function to replace the source file path with the executable file path.all: $(TARGETS)
Indicates that all depends on all executable files, and$ make
all executable files can be generated by typing on the command line.%/target: %/*.c
Indicates a rule, compiles all files in a directory.c
into corresponding executable files, and stores them in atarget
file named in the directory..PHONY: clean
Indicates that clean is a pseudo-target, not a real file, and all executable files can be deleted by typing in the command line. where the command is used to find the file named and delete it.$ make clean
find
target