分享一個通用makefile
阿新 • • 發佈:2018-12-04
- 適合寫一些小程式的時候使用,方便快捷
- c語言 c++ 混編亦可
CROSSCOMPILER :=
EXE := test
MKDIR := mkdir
RM := rm -rf
CC := $(CROSSCOMPILER)gcc
CFLAG :=
CXX := $(CROSSCOMPILER)g++
CXXFLAG :=
LIBS := -lpthread
DIR_OBJS := objs
DIR_EXES := exes
DIR_DEPS := deps
DIRS := $(DIR_OBJS) $(DIR_EXES) $(DIR_DEPS)
EXE := $( addprefix $(DIR_EXES)/, $(EXE))
C_SRCS := $(wildcard *.c)
CXX_SRCS := $(wildcard *.cpp)
OBJS := $(C_SRCS:.c=.o) $(CXX_SRCS:.cpp=.o)
OBJS := $(addprefix $(DIR_OBJS)/, $(OBJS))
DEPS := $(C_SRCS:.c=.dep) $(CXX_SRCS:.cpp=.dep)
DEPS := $(addprefix $(DIR_DEPS)/, $(DEPS))
.PHONY : rebuild clean all
all : $( DIR_OBJS) $(DIR_EXES) $(EXE)
ifeq ("$(MAKECMDGOALS)", "all")
include $(DEPS)
endif
ifeq ("$(MAKECMDGOALS)", "")
include $(DEPS)
endif
$(EXE) : $(OBJS)
ifdef C_SRCS
ifdef CXX_SRCS
$(CXX) -o [email protected] $(OBJS) $(LIBS)
else
$(CC) -o [email protected] $(OBJS) $(LIBS)
endif
else
ifdef CXX_SRCS
$(CXX) -o [email protected] $(OBJS) $(LIBS)
endif
endif
$(DIRS) :
$(MKDIR) [email protected]
$(DIR_OBJS)/%.o : %.c
$(CC) -o [email protected] -c $(filter $(C_SRCS), $^)
$(DIR_OBJS)/%.o : %.cpp
$(CXX) $(CXXFLAG) -o [email protected] -c $(filter $(CXX_SRCS), $^)
ifeq ("$(wildcard $(DIR_DEPS))", "")
$(DIR_DEPS)/%.dep : $(DIR_DEPS) $(C_SRCS) $(CXX_SRCS)
else
$(DIR_DEPS)/%.dep : $(C_SRCS) $(CXX_SRCS)
endif
@echo "Creating [email protected] ..."
@set -e; \
$(CC) -MM -E $(filter $(C_SRCS) $(CXX_SRCS), $^) | sed 's,\(.*\)\.o[ :]*,objs/\1.o [email protected] : ,g' > [email protected]
rebuild : clean all
clean :
$(RM) $(DIRS)