Makefile 遞歸遍歷目錄(含子目錄) 編譯動態庫

這裏推薦一本書,Makefile手冊,寫的挺好的~

一、統一編譯所有子目錄的文件

直接上Makefile內容了,

AR=ar
LD=ld
CC=gcc

CFLAGS = -O2 -Wall  -I./Test \
                -I./Test/Test1 \

#注:"\"後面不能有空格,並且該句寫完後最好有個換行

#註釋部分推薦在單獨的一行編寫

 

#動態庫需要 -fPIC  -shared

SOFLAGS = -O2 -fPIC -shared
TARGET = ./libSDK.so

#這裏遞歸遍歷3級子目錄
DIRS := $(shell find . -maxdepth 3 -type d)

#這裏循環遍歷目錄的cpp文件

FILES = $(foreach dir,$(DIRS),$(wildcard $(dir)/*.cpp))

#定義宏

DEF = -DLINUX -DENABLE_EPOLL

#替換文件後綴 ,也可以寫成 OBJS = $(FILES:%.cpp=%.o)

OBJS = $(patsubst %.cpp,%.o, $(FILES))
# Search paths
VPATH =

.cpp.o:
        $(CC) -c $(CFLAGS) $(DEF) -D__cplusplus $< -o $@
.c.o:
        $(CC) -c  $(CFLAGS)   $< -o $@


LIBS = -lpthread -lm -lstdc++
$(TARGET):$(OBJS)
        $(CXX) $(SOFLAGS) -o $@ $(OBJS) $(LIBS)
# $(OBJS):%.o:%.cpp
#       $(CXX) $(LINKFLAGS) $(CXXFLAGS) -o $(TARGET) $(OBJS) $(LIBS)
# $(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
        $(RM) $(TARGET)
        $(RM) $(OBJS)

 

 二、按目錄編譯

   參考:http://wdtxslqnn.blog.163.com/blog/static/4424648520132220651511/

要對子目錄執行make,需要在當前目錄製作一個Makefile,遍歷所有子目錄的Makefile,並運行相應的make target. 以下是我用來編譯內核模塊的一個Makefile

#

# Reference http://www.gnu.org/software/make/manual/make.html

#

需要排除的目錄

exclude_dirs := include bin

取得當年子目錄深度爲1的所有目錄名稱

dirs := $(shell find . -maxdepth 1 -type d)

dirs := $(basename $(patsubst ./%,%,$(dirs)))

dirs := $(filter-out $(exclude_dirs),$(dirs))

避免clean子目錄操作同名,加上_clean_前綴

SUBDIRS := $(dirs)

clean_dirs := $(addprefix _clean_,$(SUBDIRS) )

#

.PHONY: subdirs $(SUBDIRS) clean

執行默認make target

$(SUBDIRS):    

$(MAKE) -C $@

subdirs: $(SUBDIRS)

執行clean

$(clean_dirs):    

$(MAKE) -C $(patsubst _clean_%,%,$@) clean

clean: $(clean_dirs)    

@find . /        

/( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' /

-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' /

-o -name '*.symtypes' /) /

-type f -print | xargs rm -f

 

三、編譯錯誤多的情況

當我們執行make之後,發現出現的錯誤和警告信息較多,無法從頭開始查看,這裏提供一種shell的重定向輸出到文件的方法

make  2> make_print.txt 

數字    含義                   標準叫法
0      標準輸入        stdin = standard input
1      標準輸出        stdout = standard output
2      標準錯誤輸出   stderr = standard error

這樣終端就看不到錯誤輸出,而錯誤輸出都會保存在make_print.txt中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章