且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为 C/C++ 中的项目的 makefile 生成依赖项

更新时间:2022-06-12 22:19:40

GNU make 的文档提供了一个很好的解决方案.

GNU make's documentation provides a good solution.

当然.g++ -MM <your file> 将生成一个与 GMake 兼容的依赖项列表.我使用这样的东西:

Absolutely. g++ -MM <your file> will generate a GMake compatible list of dependencies. I use something like this:

# Add .d to Make's recognized suffixes.
SUFFIXES += .d

#We don't need to clean up when we're making these targets
NODEPS:=clean tags svn
#Find all the C++ files in the src/ directory
SOURCES:=$(shell find src/ -name "*.cpp")
#These are the dependency files, which make will clean up after it creates them
DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES))

#Don't create dependencies when we're cleaning, for instance
ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))
    #Chances are, these files don't exist.  GMake will create them and
    #clean up automatically afterwards
    -include $(DEPFILES)
endif

#This is the rule for creating the dependency files
src/%.d: src/%.cpp
    $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$<)' $< -MF $@

#This rule does the compilation
obj/%.o: src/%.cpp src/%.d src/%.h
    @$(MKDIR) $(dir $@)
    $(CXX) $(CXXFLAGS) -o $@ -c $<

注意: $(CXX)/gcc 命令必须是 前面有一个硬标签

这将自动为每个已更改的文件生成依赖项,并根据您现有的任何规则编译它们.这允许我将新文件转储到 src/ 目录中,并自动编译它们、依赖项和所有内容.

What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rule you have in place. This allows me to just dump new files into the src/ directory, and have them compiled automatically, dependencies and all.