使用GCC的C makefile - 从子文件夹列表中生成源文件列表

c++ makefile using gcc - generate source file list from a list of subfolders

本文关键字:列表 文件夹 源文件 GCC makefile 使用      更新时间:2023-10-16

所以我有一些有效的规则:

# Folders
SRCDIR = src
SUBFOLDERS = test test/test2
OBJDIR = obj
# Just for me so I can read my own makefile :o
_TARGET = $@
_DEPEND = $<
# Get sources from /src and /src/test/ and /src/test/test2/
SOURCES = $(wildcard $(SRCDIR)/*.cpp ))
SOURCES = $(wildcard $(SRCDIR)/test/*.cpp ))
SOURCES = $(wildcard $(SRCDIR)/test/test2/*.cpp ))
OBJECTS = $(addprefix $(OBJDIR)/, $(patsubst src/%, %, $(SOURCES:.cpp=.o))
# Main target 'make debug'
debug: debugging $(OBJECTS)
    @echo building: gcc $(OBJECTS) -o out.exe
# Compiling each file
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
    g++ -c $(_DEPEND) -o $(_TARGET)
debugging:
    @echo $(SOURCES)
    @echo $(OBJECTS)

注意:我必须手工浏览此代码,因此可能会有一些错误,但希望它清楚我要做什么。

假设我想添加更多源文件子文件夹:src/another, src/andanother。现在,我必须添加更多SOURCES = ...行才能做到这一点。有没有办法在规则中做到这一点。我一直在修改它,但我无法提出有效的规则。我想要的是,我将一个新文件夹添加到SUBFOLDERS列表中,我的代码自动拾取.cpp文件。

注意我不想使用诸如$(shell find ... )之类的东西,因为Windows发现很烂,我希望它与Possiblt Windows/Linux一样便携。

您可以使用make foreach。喜欢:

SOURCES = $(foreach dir,${SUBFOLDERS},$(wildcard ${dir}/*.cpp))

更多信息:https://www.gnu.org/software/make/manual/html_node/foreach-function.html