【发布时间】:2021-09-16 00:57:25
【问题描述】:
我目前正在尝试编写一个 Makefile,它在当前目录和所有子目录中搜索 C++ 文件,然后一一编译它们(如果它们还没有被编译或编辑自上次编译以来)到位置 ./Objects 的单个 Object 文件中,然后最终使用 Object 文件并将它们全部链接到最终程序中。
我已经知道如何使用“shell find”命令来查找所有文件。但是,我一直在试图弄清楚如何将源文件一次编译成一个目标文件。
这是我的代码:
Appname := App
#The Directory
ObjectsDir := ./Objects
#Find all the source files
SrcFiles = $(shell find . -name "*.cpp")
#Get their names only
SrcFilesName = $(notdir $(SrcFiles))
#Add a .o suffix for the Object files name
ObjectsSuffix = $(addsuffix .o, $(SrcFilesName))
#Add the prefix "Objects/" as I wish to output all the objects to ./Objects
#A Source Files such as "./Test/Source/Test.cpp" becomes "./Objects/Test.cpp.o"
Objects = $(addprefix ./Objects/, $(ObjectsSuffix))
#Compiler related Variables
CXX = g++
CXXFLAGS = -Wall -std=c++20 -fsanitize=address
CPPFLAGS = -DDEBUG -I ./Game/Headers -I ./Engine/Headers -I ./Engine/Headers/External
LDLIBS = $(shell sdl2-config --libs) -l dl
all : $(Appname)
$(Appname) : $(Objects)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(Objects) -o $(Appname) $(LDLIBS)
#The Problematic rule
#I would like this to run once per source file if they haven't been compiled or changed/edited, so that I don't end up recompiling the entire code base
$(ObjectsDir)/%.o: %.cpp
mkdir -p Objects
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -MMD -MP -c $^ -o $@ $(LDLIBS)
注意:当所有源文件都在基本目录中时,makefile 当前可以工作。但是,当布局更复杂时,会出现多个子目录错误,例如make: *** No rule to make target 'Objects/Engine.cpp.o', needed by 'App'. Stop.。
【问题讨论】: