简体   繁体   English

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

[英]generate dependencies for a makefile for a project in C/C++

I have a project that has a makefile with broken dependencies. 我有一个项目,该文件的makefile的依赖项已损坏。 Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script? 除了手动检查或使用手写的Perl脚本检查每个源文件之外,是否有任何最知名的方法来生成我可以在Makefile中使用的项目的依赖关系列表?

GNU make 's documentation provides a good solution. GNU make的文档提供了一个很好的解决方案。

Absolutely. 绝对。 g++ -MM <your file> will generate a GMake compatible list of dependencies. g++ -MM <your file>将生成GMake兼容的依赖关系列表。 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 $<

Note: $(CXX) / gcc command must be preceded with a hard tab 注意: $(CXX) / gcc命令之前必须带有一个硬选项卡

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. 这使我可以将新文件转储到src/目录中,并自动编译它们,依赖项和所有文件。

Having now read this portion in particular I think there is a much easier solution out there, as long as you have a reasonably up to date version of gcc/g++. 现在特别阅读了这一部分,我认为,只要您有一个最新的gcc / g ++版本,那里的解决方案就容易得多。 If you just add -MMD to your CFLAGS , define a variable OBJS representing all your object files, and then do: 如果仅将-MMD添加到CFLAGS ,请定义代表所有目标文件的变量OBJS ,然后执行以下操作:

-include $(OBJS:%.o=%.d)

then that should get you both an efficient and simple automatic dependency build system. 那么这将使您既高效又简单的自动依赖项构建系统。

GNU C预处理程序cpp具有-MM选项,该选项根据包含模式生成适合的一组依赖关系。

I just add this to the makefile and it works nicely: 我只是将其添加到makefile中,并且效果很好:

-include Makefile.deps

Makefile.deps:
    $(CC) $(CFLAGS) -MM *.[ch] > Makefile.deps

Digital Mars C / C ++编译器带有makedep工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM