实例奉上如何优雅地编写Makefile!

  Makefile章节的物语很久没更新了,本次带来的是如何编写一份简单实用的Makefile,算得上是之前的几篇入门总结的集小成者,下面这个实例很简单,是我在实际编程中所使用的一个demo,略有英文注释,一看便明。
  ●-编译过程的中间文件放置于BUILD_DIR 中;
  ●-编译生成的执行文件放置于OBJ_DIR 中;
  ●-目标文件为TARGET
  ●-源码目录为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 "********************"

猜你喜欢

转载自blog.csdn.net/qq_33475105/article/details/115011802