这是第一个亲手写出的Makefile,能够自动实现工程目录的创建和相应文件的生成与清除。
该工程的目录摘自小结一中的书籍。
源码中的注释解释的是一种从单个目录到工程环境的创建过程中的改动之处。
工程中仅有一个源文件Hello.c
大体的makefile如下:
1)公有Makefile改名叫make.rule
2)模块独立的Makefile编译生成每个模块的相应依赖和目标
- .PHONY:all clean
-
-
CC = gcc
-
RM = rm
-
RMFLAGS = -rf
-
MKDIR = mkdir
-
AR = ar
-
ARFLAGS = crs
-
-
#此代码为各个Makefile的公有部分
-
#仅仅修改了DIR_LIBS DIR_EXES路径值,删除了EXE LIB赋值操作,因为他们在子模块中各有不同
-
-
DIR_OBJS = objs
-
DIR_DEPS = deps
-
DIR_LIBS = $(ROOT)/build/libs
-
DIR_EXES = $(ROOT)/build/exes
-
DIRS = $(DIR_OBJS) $(DIR_DEPS) $(DIR_LIBS) $(DIR_EXES)
-
RMS = $(DIR_DEPS) $(DIR_OBJS)
-
-
#LIB = libfoo.a
-
ifneq ("$(LIB)","")
-
LIB := $(addprefix $(DIR_LIBS)/,$(LIB))
-
RMS += $(LIB)
-
endif
-
-
#EXE = complicated
-
ifneq ("$(EXE)","")
-
EXE := $(addprefix $(DIR_EXES)/,$(EXE))
-
RMS += $(EXE)
-
endif
-
-
SRCS = $(wildcard *.c)
-
OBJS = $(SRCS:.c=.o)
-
OBJS := $(addprefix $(DIR_OBJS)/,$(OBJS))
-
DEPS = $(SRCS:.c=.dep)
-
DEPS := $(addprefix $(DIR_DEPS)/,$(DEPS))
-
-
ifeq ("$(wildcard $(DIR_EXES))","")
-
DEP_DIR_EXES := $(DIR_EXES)
-
endif
-
ifeq ("$(wildcard $(DIR_OBJS))","")
-
DEP_DIR_OBJS := $(DIR_OBJS)
-
endif
-
ifeq ("$(wildcard $(DIR_DEPS))","")
-
DEP_DIR_DEPS := $(DIR_DEPS)
-
endif
-
ifeq ("$(wildcard $(DIR_LIBS))","")
-
DEP_DIR_LIBS := $(DIR_LIBS)
-
endif
-
-
all:$(EXE) $(LIB)
-
-
ifneq ($(MAKECMDGOALS),clean)
-
include $(DEPS)
-
endif
-
-
$(DIRS):
-
$(MKDIR) $@
-
-
$(EXE): $(DEP_DIR_EXES) $(OBJS)
-
$(CC) -o $@ $(filter %.o,$^)
-
$(LIB): $(DEP_DIR_LIBS) $(OBJS)
-
$(AR) $(ARFLAGS) $@ $(filter %.o,$^)
-
$(DIR_OBJS)/%.o: $(DEP_DIR_OBJS) %.c
-
$(CC) -o $@ -c $(filter %.c,$^)
-
$(DIR_DEPS)/%.dep: $(DEP_DIR_DEPS) %.c
-
@echo "Creating $@ ..."
-
@set -e ; \
-
$(RM) $(RMFLAGS) $@.tmp ; \
-
$(CC) -E -MM $(filter %.c,$^) > $@.tmp ; \
-
sed 's,\(.*\)\.o[ :]*,objs/\1.o $@: ,g' < $@.tmp > $@ ; \
-
$(RM) $(RMFLAGS) $@.tmp
-
-
clean:
-
$(RM) $(RMFLAGS) $(RMS)
make.rule
- LIB = libfoo.a
-
EXE =
-
include $(ROOT)/build/make.rule
子目录foo模块Makefile
- #此处生成可执行文件,路径需要用export制定,以便后续所有shell都能用到
-
LIB =
-
EXE = complicated
-
include $(ROOT)/build/make.rule
阅读(1502) | 评论(0) | 转发(0) |