Write a Makefile to compile the .c files in each directory into their respective 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.

The following is an example Makefile, assuming that each directory has a .csource 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: %/*.cIndicates a rule, compiles all files in a directory .c into corresponding executable files, and stores them in a targetfile named in the directory.
  • .PHONY: cleanIndicates 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 cleanfind target

Guess you like

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