Makefile常用函数
1. 获取当前目录下的所有同一类型的文件
$(wildcard *.h) 、$(wildcard *.c *.cpp)
2. 批量处理某一类型文件(替换、添加)
$(patsubst %.c, %.o, $(SRC))
$(patsubst %, -I %, $(INCDIRS))
3. 提取每一个目录下的 .c 文件
$(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c))
4. 将 CFILES 中的路径去掉 dev/adc.c => adc.c
$(notdir $(CFILES))
5. 给 OBJS 加路径前缀,使其变成完整路径的形式
OBJS := $(addprefix $(OBJ_DIR)/,$(OBJS))
6. 根据 .c 推导出 .o
OBJS = $(SRCS:.c=.o)
1. 单个目录(最简单的Makefile)
CROSS_COMPILE ?=
CC := $(CROSS_COMPILE)gcc
EXECUTABLE := bsp_test
INCLUDES := $(wildcard *.h)
SRC := $(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(SRC))
CPPFLAGS := --std=c++11
RM-F := rm -rf
.PHONY : clean
$(EXECUTABLE) : $(OBJS)
@echo "输出变量OBJS的值,方便调试"
@echo $(OBJS)
$(CC) -o $(EXECUTABLE) $(OBJS) $(CPPFLAGS)
%.o : %.c $(INCLUDES)
$(CC) -c $< -o $@ $(CPPFLAGS)
clean:
$(RM-F) $(EXECUTABLE) $(OBJS)
2. 多层目录(单个Makefile构建BSP)
CROSS_COMPILE ?=
TARGET ?= bsp_test
CC := $(CROSS_COMPILE)gcc
INCDIRS := device/adc \
device/serialport \
include \
include/debug \
SRCDIRS := user \
device/adc \
device/serialport \
INCLUDE := $(patsubst %, -I %, $(INCDIRS))
CFILES := $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c))
CFILENDIR := $(notdir $(CFILES))
OBJS := $(patsubst %, obj/%, $(CFILENDIR:.c=.o))
VPATH := $(SRCDIRS)
.PHONY: clean
$(TARGET).bin : $(OBJS)
$(CC) $^ -o $@
clean:
rm -rf $(TARGET).elf $(TARGET).dis $(TARGET).bin $(COBJS)
3. 多层目录(多个Makefile嵌套管理,类似于内核)
顶层Makefile: vim Makefile
CROSS_COMPILE ?=
TARGET ?= bsp_test
CC := $(CROSS_COMPILE)gcc
MAKE := make
TOP_DIR := $(shell pwd)
OBJ_DIR := $(TOP_DIR)/obj
INCDIRS := device/adc \
device/serialport \
include \
include/debug \
SUB_DIR := device/adc \
device/serialport \
user
INCLUDE := $(patsubst %, -I %, $(INCDIRS))
CFILES := $(foreach dir, $(SUB_DIR), $(wildcard $(dir)/*.c))
CFILENDIR := $(notdir $(CFILES))
OBJS := $(patsubst %, obj/%, $(CFILENDIR:.c=.o))
CFLAGS = -g -Wall
export CC MAKE TOP_DIR OBJ_DIR SUB_DIR INCLUDE CFLAGS
.PHONY: clean
all: $(SUB_DIR) $(TARGET)
$(SUB_DIR) :
$(MAKE) -C $@
$(TARGET): $(OBJS)
$(CC) -g -o $@ $^
@echo "make $(TARGET) done!"
@echo ""
clean:
rm -rf $(OBJ_DIR )/*.o
rm -rf $(TARGET)
device/adc/Makefile 、 device/serialport /Makefile 和 user/Makefile 同理
SRCS = $(wildcard *.c)
OBJS = $(SRCS:.c=.o)
OBJS := $(addprefix $(OBJ_DIR)/,$(OBJS))
.PHONY: taskslocal
taskslocal: $(OBJS)
$(OBJ_DIR)/%.o: %.c
$(CC) -g -c $(CFLAGS) $(INCLUDE) -o $@ $<
|