我如何在Makefile中的子目录中递归找到源文件



我是Makefile的新手,但我仍然不明白如何设置源文件的子目录。

我的目录树是:

i18n/
src/
    engine/
    graphics/ (currently only directory used)

我正在使用此预制Makefile

TARGET = caventure
LIBS = -lSDL2
CC = g++
CFLAGS = -Wall
TGTDIR = build
.PHONY: default all clean
default: $(TARGET)
all: default
OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))
HEADERS = $(wildcard *.h)
%.o: %.cpp $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@
.PRECIOUS: $(TARGET) $(OBJECTS)
$(TARGET): $(OBJECTS)
    $(CC) $(OBJECTS) -Wall $(LIBS) -o $(TGTDIR)/$(TARGET)
clean:
    -rm -f *.o
    -rm -f $(TARGET)

gnu make的 wildcard函数不会递归访问所有子目录。您需要它的递归变体,可以按照以下答案所述实现:

https://stackoverflow.com/a/18258352/1221106

因此,您需要使用递归通配符功能而不是$(wildcard *.cpp)

递归查找文件的另一种更简单的方法可能只是使用find

例如,如果您有这样的布局。

$ tree .
.
├── d1
│   └── foo.txt
├── d2
│   ├── d4
│   │   └── foo.txt
│   └── foo.txt
├── d3
│   └── foo.txt
└── Makefile

您可以像这样写一个makefile。

index.txt: $(shell find . -name "*.txt")                                             
    echo $^                                                                           

打印此。

$ make
echo d2/d4/foo.txt d2/foo.txt d1/foo.txt d3/foo.txt
d2/d4/foo.txt d2/foo.txt d1/foo.txt d3/foo.txt

最新更新