makefile 中的自动依赖生成

Autodependency generation in makefiles

我试图了解在给定 link 的 makefile 中如何生成自动依赖性,我无法理解以下代码:

DEPDIR = .deps
df = $(DEPDIR)/$(*F)

SRCS = foo.c bar.c ...

%.o : %.c
        @$(MAKEDEPEND); \
          cp $(df).d $(df).P; \
          sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\$$//' \
              -e '/^$$/ d' -e 's/$$/ :/' < $(df).d >> $(df).P; \
          rm -f $(df).d
        $(COMPILE.c) -o $@ $<

-include $(SRCS:%.c=$(DEPDIR)/%.P)

我从 this link. 得到它我知道它会生成依赖文件,但我无法理解这一行的作用:

sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\$$//' \
    -e '/^$$/ d' -e 's/$$/ :/' < $(df).d >> $(df).P; \

谁能给我解释一下这段代码,这么多通配符让我大吃一惊,我是 makefile 的新手。

这是许多不同的命令,所以将其分解。

  1. -e 's/#.*//'

    删除所有以 # 开头的内容(注释?预处理器指令?)

  2. -e 's/^[^:]*: *//'

    删除任何有 : : 之前的所有内容。

  3. -e 's/ *\$$//'

    删除行尾的续行斜杠(及其前面的空格)。

  4. -e '/^$$/ d'

    删除所有空行。

  5. -e 's/$$/ :/'

    在每行末尾添加 :

这会为每个列出的依赖文件添加显式目标,以便 make“知道”如何构建它们以避免“无规则创建目标”错误。 an earlier section.

中的 link 解释了这里的推理

Briefly, this creates a .P file with the original prerequisites list, then adds targets to it by taking each line, removing any existing target information and any line continuation (\) characters, then adding a target separator (:) to the end. This works with the values for MAKEDEPEND I suggest below; it’s possible you will need to modify the translation for other dependency generators you might use.

这并不是要回答您的实际问题,但既然您说您是 GNU make 的新手,我认为传播存在处理自动依赖项的更简单方法的说法不会有任何坏处。

现在 GCC 或 Clang 等编译器可以在编译代码时为您完成这项工作!

简单地传递给他们一个预处理器标志:

# Preprocessor flags
CPPFLAGS += -MMD

并将生成的文件包含到 Makefile 中:

-include $(wildcard *.d)

大功告成。


您可以了解有关预处理器选项的更多信息here for GCC,Clang 只是镜像这些选项。

一个比较好的例子也在here