本文介绍了在makefile中使用g++和-MMD自动生成依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道下面的 makefile 将使预处理器自动生成依赖项(在 .d 文件中)并将它们包含在 makefile 中(因为我的课程笔记是这样说的),因此它们不必自动维护.-MMD 标志对此负责.我不明白的是: .d 文件是在什么时候生成的?甚至没有使用 ${CXXFLAGS} 的任何命令.据推测,像 ${CXX} ${CXXFLAGS} -c xC -o xo 这样的命令将由 make 自动为每个目标文件推导出来,但如果这些是生成 .d 文件的命令,如果我们只通过执行生成这些 .o 文件的命令来了解它们,我们是否已经通过了了解 xo、yo 和 zo 的依赖关系的点?(假设有 .h 文件,如果让其自行推断规则或其他东西,makefile 将忽略这些文件.)

I know the following makefile will have the pre-processor automatically generate dependencies (in .d files) and include them in the makefile (because my course notes say so), so that they do not have to be automatically maintained. The -MMD flag is what's responsible for this. What I don't get is: At what point are the .d files generated? There isn't even any command where ${CXXFLAGS} is used. Presumably, commands like ${CXX} ${CXXFLAGS} -c x.C -o x.o will be automatically deduced by make for each of the object files, but if these are the commands that generate the .d files, wouldn't we have already passed the point where knowing the dependencies of x.o, y.o and z.o could've been relevant, if we only know them by executing the commands that generate these .o files? (Say there are .h files that the makefile would ignore if left to deduce the rules on its own or something.)

CXX = g++                     # compiler
CXXFLAGS = -g -Wall -MMD      # compiler flags
OBJECTS = x.o y.o z.o         # object files forming executable
DEPENDS = ${OBJECTS:.o=.d}    # substitutes ".o" with ".d"
EXEC = a.out                  # executable name

${EXEC} : ${OBJECTS}          # link step
    ${CXX} ${OBJECTS} -o ${EXEC}

-include ${DEPENDS}           # copies files x.d, y.d, z.d (if they exist)

推荐答案

你说得对.第一次运行 Makefile 时,依赖项不存在.

You're correct here. The dependencies aren't present the first time the Makefile is run.

但这没关系 - 仅当 .o 文件已经存在并且您更改了 .h 文件时才需要依赖信息.第一次运行 Make 时,无论如何都需要构建所有 .o 文件,同时生成 .d 文件.

But this doesn't matter - the dependency information is only needed when .o files are already present, and you've changed a .h file. The first time you run Make, all .o files will need to be built anyway, and the .d files are generated at the same time.

之后,.d 文件会给出依赖信息.如果一个头被改变,依赖信息会告诉 Make 哪些 .o 文件需要重建.如果源文件发生变化,总是需要重新构建.o,同时会生成更新的依赖信息.

After that, the .d files will give dependency information. If a header is changed, the dependency information will tell Make which .o files need rebuilding. If a source file is changed, the .o will always need to be rebuilt, and updated dependency information will be generated at the same time.

这篇关于在makefile中使用g++和-MMD自动生成依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:03