代码改变世界

Makefile for C/C++

2012-12-02 14:27  robturtle  阅读(331)  评论(0编辑  收藏  举报

Makefile for C/C++

功能:分析工作目录下的依赖关系,并根据依赖关系编译链接生成可执行文件

# Template version: 1.0.1
# Date: 2012/11/10 11:48
# Maintainer: Liu Yang

######################
# Customized Settings #
######################
OUTPUT := demo
VPATH := /home/ben/include
LIB := /home/ben/lib
opt :=## Example opt=-lcurse -lm -pthread #
CC := gcc -std=c99
CCPP := g++
CPPFLAGS := -Wall
DEBUG := -D DEBUG -g
RELEASE := -O2

###########################
# Auto Arguments Settings #
###########################
sources = $(shell ls)
ifeq (.cpp,$(findstring .cpp,$(sources)))
CC := $(CCPP)
endif
c_files = $(filter %.c, $(sources))
cpp_files = $(filter %.cpp, $(sources))
OBJ = $(patsubst %.cpp,%.o,$(cpp_files))
OBJ += $(patsubst %.c,%.o,$(c_files))
OBJD = $(OBJ:.o=.d)
CPPFLAGS += $(patsubst %,-I%,$(subst :, ,$(VPATH)))
%.d: %.c
set -e; rm -f $@; \
$(CC) $(CPPFLAGS) -M $< > $@.$$$$; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$
%.d: %.cpp
set -e; rm -f $@; \
$(CC) $(CPPFLAGS) -M $< > $@.$$$$; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$

########################
# Target Prerequisites #
########################
$(OUTPUT):$(OBJ)
$(CC) $(OBJ) $(CPPFLAGS) -L$(LIB) $(opt) -o $(OUTPUT)
-include $(OBJD)

##########################
# Optional Make Commands #
##########################
.PHONY:clean cleanobj debug release
debug : CPPFLAGS += $(DEBUG)
debug:cleanobj $(OBJ)
$(CC) $(OBJ) $(CPPFLAGS) -L $(LIB) $(opt) -o $(addsuffix .debug,$(OUTPUT))
release: CPPFLAGS += $(RELEASE)
release:cleanobj $(OBJ)
$(CC) $(OBJ) $(CPPFLAGS) -L $(LIB) $(opt) -o $(addsuffix .release,$(OUTPUT))
clean: cleanobj
-rm $(OUTPUT)
cleanobj:
-rm $(OBJ) $(OBJD)