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\n"
$(OBJS) : $(OBJ_DIR)/%.o:%.$(TYPE)
@mkdir -p $(@D)
@echo "Compiling" $@ "from" $< "..."
$(CC) -c -o $@ $< $(C_FLAGS) $(INCLUDES)
@echo "Compile finished\n"
.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\n"
$(OBJS) : $(OBJ_DIR)/%.o:%.$(TYPE)
@mkdir -p $(@D)
@echo "Compiling" $@ "from" $< "..."
$(CC) -c -o $@ $< $(C_FLAGS) $(INCLUDES)
@echo "Compile finished\n"
.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/