在阅读了 cdhowie 的回答后,我开始研究 mkdep,但似乎此类程序已被弃用,并且已被执行相同操作的编译器标志所取代。我已经包含了我的 makefile 的主体,它编译了主程序(srcpath 中的代码)和测试(testpath 中的代码)然后运行测试。在此期间创建了两个单独的依赖文件,一个用于 main,另一个用于测试。
src = $(shell cd $(srcpath); find ./ -name "*.cpp")
testsrc = $(shell cd $(testpath); find ./ -name "*.cpp")
obj = $(src:%.cpp=%.o)
testobj = $(testsrc:%.cpp=%.o)
head = $(shell cd $(srcpath); find ./ -name "*.h")
testhead = $(shell cd $(testpath); find ./ -name "*.h")
skip_files = ./main.o
makedep = $(shell $(cpp) $(cflags) -MM -MT '$(patsubst $(srcpath)%.cpp, $(objpath)%.o, $(file))' $(file) >> .depend)
makedeptest = $(shell $(cpp) $(cflags) -MM -MT '$(patsubst $(testpath)%.cpp, $(testobjpath)%.o, $(file))' $(file) >> .dependtest)
all: main Test
Test: .dependtest $(addprefix $(testobjpath),$(testobj))
@echo "Linking Tests"
@$(cpp) $(lflags) -o $(testbin) $(addprefix $(testobjpath), $(testobj)) $(addprefix $(objpath), $(filter-out $(skip_files),$(obj)))
@./$(testbin)
.dependtest: $(addprefix $(testpath), $(testsrc)) $(addprefix $(testpath), $(testhead))
$(shell rm -f .dependtest)
$(foreach file,$(addprefix $(testpath), $(testsrc)), $(makedeptest))
$(addprefix $(testobjpath), %.o): $(addprefix $(testpath), %.cpp)
$(cpp) $(cflags) -c -o $@ $<
main: .depend $(addprefix $(objpath), $(obj))
@echo "Linking Program"
@$(cpp) $(lflags) -o $(bin) $(addprefix $(objpath),$(obj))
.depend: $(addprefix $(srcpath), $(src)) $(addprefix $(srcpath), $(head))
$(shell rm -f .depend)
$(foreach file, $(addprefix $(srcpath), $(src)), $(makedep))
$(addprefix $(objpath), %.o): $(addprefix $(srcpath), %.cpp)
$(cpp) $(cflags) -c -o $@ $<
clean:
-rm $(testbin) $(bin) $(addprefix $(objpath),$(obj)) $(addprefix $(testobjpath),$(testobj))
-include .depend
-include .dependtest