一点一点学写Makefile(6)-遍历当前目录源文件及其子目录下源文件

时间:2023-03-10 02:39:47
一点一点学写Makefile(6)-遍历当前目录源文件及其子目录下源文件

时候,我们在开发的时候需要将本次工程的代码分成多个子目录来编写,但是在Makefile的编写上却是个问题,下面我就教大家怎么构建带有子文件夹的源代码目录的自动扫描编译

下面这张图是我的文件树

一点一点学写Makefile(6)-遍历当前目录源文件及其子目录下源文件

这里面src目录下是我的源代码,我将功能代码分成了三个子模块,分别为test1, test2, test3, 调用这三个子模块的是main.cpp文件,下面我将这三个子模块的代码

  1. //  src/test1/test1.h
  2. #ifndef __TEST1_H__
  3. #define __TEST1_H__
  4. int test1();
  5. #endif //__TEST1_H__
  6. // src/test1/test1.cpp
  7. #include "test1.h"
  8. int test1() {
  9. return 1;
  10. }
  11. <pre name="code" class="cpp">//  src/test2/test2.h
  12. #ifndef __TEST2_H__
  13. #define __TEST2_H__
  14. int test2();
  15. #endif //__TEST2_H__
  16. // src/test2/test2.cpp
  17. #include "test2.h"
  18. int test2() {
  19. return 2;
  20. }
  1. //  src/test3/test3.h
  2. #ifndef __TEST3_H__
  3. #define __TEST3_H__
  4. int test3();
  5. #endif //__TEST3_H__
  6. // src/test3/test3.cpp
  7. #include "test3.h"
  8. int test3() {
  9. return 3;
  10. }

// 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遍历的核心代码如下:

  1. SRC_PATH = ./src
  2. DIRS = $(shell find $(SRC_PATH) -maxdepth 3 -type d)
  3. # 为了更大幅度的支持项目的搭建,将三种文件格式的后缀都单独便利到变量中
  4. SRCS_CPP += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cpp))
  5. SRCS_CC += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.cc))
  6. SRCS_C += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.c))
  7. OBJS_CPP = $(patsubst %.cpp, %.o, $(SRCS_CPP))
  8. OBJS_CC = $(patsubst %.cc, %.o, $(SRCS_CC))
  9. OBJS_C = $(patsubst %.c, %.o, $(SRCS_C))

下面是Makefile的全部文件