Write Makefile to compile all .c files in a directory into executable files

The process of writing a Makefile is as follows:

  1. Define variables: Define variables such as compiler and compilation options.
  2. Define target file: Define the target file name.
  3. Define source files: Define all source files.
  4. Define rules: Define the rules for compiling each source file into an object file.
  5. 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 *.cto find all files ending with in the current directory. .c
  • TARGETSis 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: cleanIndicates that clean is a pseudo-target, not a real file, and $ make cleanall executable files can be deleted by typing in the command line.

Guess you like

Origin blog.csdn.net/FLM19990626/article/details/130983496