Makefile模板
TARGET = ${notdir $(CURDIR)}
SRC_DIR = .
SRC_SUBDIR += .
INCLUDE_DIR += .
OBJ_DIR = .
CC = gcc
C_FLAGS = -g -Wall
LD = $(CC)
INCLUDES += -I$(INCLUDE_DIR)
LD_FLAFS +=
LD_LIBS =
ifeq ($(CC), g++)
TYPE = cpp
else
TYPE = c
endif
SRCS += ${foreach subdir, $(SRC_SUBDIR), ${wildcard $(SRC_DIR)/$(subdir)/*.$(TYPE)}}
OBJS += ${foreach src, $(notdir $(SRCS)), ${patsubst %.$(TYPE), $(OBJ_DIR)/%.o, $(src)}}
vpath %.$(TYPE) $(sort $(dir $(SRCS)))
all : $(TARGET)
@echo "Builded target:" $^
@echo "Done"
$(TARGET) : $(OBJS)
@mkdir -p $(@D)
@echo "Linking" $@ "from" $^ "..."
$(LD) -o $@ $^ $(LD_FLAGS) $(LD_LIBS)
@echo "Link finished
"
$(OBJS) : $(OBJ_DIR)/%.o:%.$(TYPE)
@mkdir -p $(@D)
@echo "Compiling" $@ "from" $< "..."
$(CC) -c -o $@ $< $(C_FLAGS) $(INCLUDES)
@echo "Compile finished
"
.PHONY : clean cleanobj
clean : cleanobj
@echo "Remove all executable files"
rm -f $(TARGET)
cleanobj :
@echo "Remove object files"
rm -rf $(OBJ_DIR)/*.o
用法
编译C程序
make
编译C++程序
make CC=g++
或者将Makefile中的CC = gcc
改成CC = g++
,然后
make
其他
TARGET
指定生成的可执行文件名,我这里用的是当前所在目录名
SRC_DIR
指定源文件(.c .cpp)文件的路径, 如SRC_DIR = ./src
SRC_SUBDIR
列举SRC_DIR下的子目录, 如SRC_DIR下有子目录"utils", SRC_SUBDIR += . utils
INCLUDE_DIR
指定头文件路径, 如INCLUDE_DIR += ./include
OBJ_DIR
指定中间文件存放路径, 如OBJ_DIR = ./obj
C_FLAGS
指定编译参数选项
LD_FLAFS
指定链接参数选项
LD_LIBS
指定链接库, 如LD_LIBS += -lm
清除生成的文件:
# 清空全部生成文件
make clean
# 清空生成的中间文件
make cleanobj
Tips
对于Ubuntu系统,可以将Makefile文件复制到~/Templates(中文环境为~/模板)目录下,这样就可以在任意目录下右键添加该Makefile模板。
终端输入:
gedit ~/.bashrc
在~/.bashrc文件中添加一行
alias Makefile="cp ~/Templates/Makefile ./"
保存后输入:
source ~/.bashrc
生效之后,就可以通过在命令行输入Makefile
,来创建Makefile模板了。
OpenCV Makefile模板
TARGET = ${notdir $(CURDIR)}
SRC_DIR = .
SRC_SUBDIR += .
INCLUDE_DIR += .
OBJ_DIR = .
CC = g++
C_FLAGS = -g -Wall
LD = $(CC)
INCLUDES += -I$(INCLUDE_DIR)
-I/usr/local/include/opencv4/
-I/usr/local/include
LD_FLAGS += -L/usr/local/lib/
LD_LIBS += -lopencv_core
-lopencv_highgui
-lopencv_imgcodecs
-lopencv_imgproc
ifeq ($(CC), g++)
TYPE = cpp
else
TYPE = c
endif
SRCS += ${foreach subdir, $(SRC_SUBDIR), ${wildcard $(SRC_DIR)/$(subdir)/*.$(TYPE)}}
OBJS += ${foreach src, $(notdir $(SRCS)), ${patsubst %.$(TYPE), $(OBJ_DIR)/%.o, $(src)}}
vpath %.$(TYPE) $(sort $(dir $(SRCS)))
all : $(TARGET)
@echo "Builded target:" $^
@echo "Done"
$(TARGET) : $(OBJS)
@mkdir -p $(@D)
@echo "Linking" $@ "from" $^ "..."
$(LD) -o $@ $^ $(LD_FLAGS) $(LD_LIBS)
@echo "Link finished
"
$(OBJS) : $(OBJ_DIR)/%.o:%.$(TYPE)
@mkdir -p $(@D)
@echo "Compiling" $@ "from" $< "..."
$(CC) -c -o $@ $< $(C_FLAGS) $(INCLUDES)
@echo "Compile finished
"
.PHONY : clean cleanobj
clean : cleanobj
@echo "Remove all executable files"
rm -f $(TARGET)
cleanobj :
@echo "Remove object files"
rm -rf $(OBJ_DIR)/*.o
此文原创禁止转载,转载文章请联系博主并注明来源和出处,谢谢!
作者: Raina_RLN https://www.cnblogs.com/raina/