繁体   English   中英

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

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

我有一个项目,该文件的makefile的依赖项已损坏。 除了手动检查或使用手写的Perl脚本检查每个源文件之外,是否有任何最知名的方法来生成我可以在Makefile中使用的项目的依赖关系列表?

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

绝对。 g++ -MM <your file>将生成GMake兼容的依赖关系列表。 我用这样的东西:

# 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/目录中,并自动编译它们,依赖项和所有文件。

现在特别阅读了这一部分,我认为,只要您有一个最新的gcc / g ++版本,那里的解决方案就容易得多。 如果仅将-MMD添加到CFLAGS ,请定义代表所有目标文件的变量OBJS ,然后执行以下操作:

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

那么这将使您既高效又简单的自动依赖项构建系统。

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

我只是将其添加到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