The example shows how to write Makefile elegantly!

  The story of the Makefile chapter hasn’t been updated for a long time. This time I brought you how to write a simple and practical Makefile. It can be regarded as a collection of the previous introductory summaries. The following example is very simple. I am actually programming. A demo used in, with a little English annotation, it is easy to see at a glance.
  ●-The intermediate file of the compilation process is placed in BUILD_DIR ;
  ●-The executable file generated by the compilation is placed in OBJ_DIR ;
  ●-The target file is TARGET ;
  ●-The source code directory is SRC_DIR ;

# name the target project
TARGET = test_demo

# compile tool
CC = gcc

BUILD_DIR = ./build
OBJ_DIR = ./bin

#SRC_DIR for source code
SRC_DIR	=./

VPATH = $(SRC_DIR)

# the path of the head files
INCLUDE_DIR=-I/usr/local/include
 
# load lib   -L load path of the lib ; -l load name of the lib
LIBS	= -lpaho-mqtt3c

# Macro definition	
DEFS = -D_POSIX_C_SOURCE=1
# compile option(-wall output warning message; -O optimize compile)
CFLAGS	= -Wall -O3 -std=c99
CFLAGS  += $(DEFS)

#replace *.c to *.o from variable SOUTCE_C, and get the name string to variable OBJECT_O 
SOURCE_C	= $(foreach dir, $(SRC_DIR), $(wildcard $(dir)/*.c))
OBJECT_O	= $(addprefix $(BUILD_DIR)/,$(patsubst %.c,%.o,$(notdir $(SOURCE_C))))

#.c.o:
$(BUILD_DIR)/%.o: %.c
	$(CC) -c $(CFLAGS) $(INCLUDE_DIR) $< -o $@
 
$(TARGET): $(OBJECT_O)
	$(CC) ${
    
    CFLAGS}   $(OBJECT_O) $(LIBS) -o $(OBJ_DIR)/$@
	@echo "********************"
	@echo "***Build Finished***"
	@echo "********************"

.PHONY: clean 
clean:
	rm $(TARGET) $(BUILD_DIR)/*.o -rf
	@echo "********************"
	@echo "***Clean Finished***"
	@echo "********************"

Guess you like

Origin blog.csdn.net/qq_33475105/article/details/115011802