時候,我們在開發的時候需要將本次工程的代碼分成多個子目錄來編寫,但是在Makefile的編寫上卻是個問題,下面我就教大家怎么構建帶有子文件夾的源代碼目錄的自動掃描編譯
下面這張圖是我的文件樹
這里面src目錄下是我的源代碼,我將功能代碼分成了三個子模塊,分別為test1, test2, test3, 調用這三個子模塊的是main.cpp文件,下面我將這三個子模塊的代碼
- // src/test1/test1.h
- #ifndef __TEST1_H__
- #define __TEST1_H__
- int test1();
- #endif //__TEST1_H__
- // src/test1/test1.cpp
- #include "test1.h"
- int test1() {
- return 1;
- }
- <pre name="code" class="cpp">// src/test2/test2.h
- #ifndef __TEST2_H__
- #define __TEST2_H__
- int test2();
- #endif //__TEST2_H__
- // src/test2/test2.cpp
- #include "test2.h"
- int test2() {
- return 2;
- }
- // src/test3/test3.h
- #ifndef __TEST3_H__
- #define __TEST3_H__
- int test3();
- #endif //__TEST3_H__
- // src/test3/test3.cpp
- #include "test3.h"
- int test3() {
- return 3;
- }
// src/main.cpp
#include <iostream>
#include "test1/test1.h"
#include "test2/test2.h"
#include "test3/test3.h"
using namespace std;
int main() {
cout << "test1()" << test1() << endl;
cout << "test2()" << test2() << endl;
cout << "test3()" << test3() << endl;
}
Makefile遍歷的核心代碼如下:
- SRC_PATH = ./src
- DIRS = $(shell find $(SRC_PATH) -maxdepth 3 -type d)
- # 為了更大幅度的支持項目的搭建,將三種文件格式的后綴都單獨便利到變量中
- SRCS_CPP += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cpp))
- SRCS_CC += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cc))
- SRCS_C += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.c))
- OBJS_CPP = $(patsubst %.cpp, %.o, $(SRCS_CPP))
- OBJS_CC = $(patsubst %.cc, %.o, $(SRCS_CC))
- OBJS_C = $(patsubst %.c, %.o, $(SRCS_C))
下面是Makefile的全部文件