Directory Structure
Since only a small program used to compile simple, so the directory as concisely as possible:
#.
#├── bin
#├── .dep
#├── makefile
#├── obj
#└── src
Here you need to create only the src directory, which put the project .h
and .cpp
files.
Automatically generated dependent header files
G ++ derived using the command header files rely on features generated for each .cpp
file corresponding to the .d
dependence file, and then .d
rely on the file include
to a makefile, enable detection of the header file dependent.
See specific principles: Auto-Dependency Generation
debug和release
Generate release version of the command: make
generates a debug version of the command: make debug
Note that the debug version and release version of the shared directory, so when do you need to switch make clean
it
makefile
#目录结构
#.
#├── bin
#├── .dep
#├── makefile
#├── obj
#└── src
#获取当前的makefile所在的目录绝对路径
#MAKEFILE_LIST是make工具定义的环境变量,最后一个值就是当前的makefile的启动路径(可能是相对路径)
TOP_DIR := $(patsubst %/, %, $(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
#各项目录
BIN_DIR := $(TOP_DIR)/bin
DEP_DIR := $(TOP_DIR)/.dep
OBJ_DIR := $(TOP_DIR)/obj
SRC_DIR := $(TOP_DIR)/src
#编译器,链接器
CXX := g++
LD := g++
#生成依赖文件选项
DEPFLAGS = -MT $@ -MMD -MP -MF $(DEP_DIR)/$*.d
#编译选项
CXXFLAGS := -std=c++11 -Wall -m64
#宏定义
MACROS :=
#链接选项
LDFLAGS :=
#包含的头文件和库文件
INCS :=
LIBS :=
#源文件以及中间目标文件和依赖文件
SRCS := $(notdir $(wildcard $(SRC_DIR)/*.cpp))
OBJS := $(addprefix $(OBJ_DIR)/, $(patsubst %.cpp, %.o, $(SRCS)))
DEPS := $(addprefix $(DEP_DIR)/, $(patsubst %.cpp, %.d, $(SRCS)))
#最终目标文件
TARGET := $(BIN_DIR)/hello
#默认最终目标
.PHONY : all
all : $(TARGET)
#debug最终目标
.PHONY : debug
debug : CXXFLAGS += -g
debug : $(TARGET)
#生成最终目标
$(TARGET) : $(OBJS) | $(BIN_DIR)
$(LD) $(LDFLAGS) $(LIBS) -o $@ $^
#若没有bin目录则自动生成
$(BIN_DIR) :
mkdir -p $@
#生成中间目标文件(release版)
$(OBJ_DIR)/%.o : $(SRC_DIR)/%.cpp $(DEP_DIR)/%.d | $(OBJ_DIR) $(DEP_DIR)
$(CXX) -c $(DEPFLAGS) $(CXXFLAGS) $(INCS) $(MACROS) -o $@ $<
#若没有obj目录则自动生成
$(OBJ_DIR) :
mkdir -p $@
#若没有.dep目录则自动生成
$(DEP_DIR) :
mkdir -p $@
#依赖文件会在生成中间文件的时候自动生成,这里只是为了防止报错
$(DEPS) :
#引入中间目标文件头文件依赖关系
include $(wildcard $(DEPS))
#删除makefile创建的目录
.PHONY : clean
clean :
rm -rf $(BIN_DIR) $(OBJ_DIR) $(DEP_DIR)