在 Makefile 中使用 `-include` 有什么实际原因吗?

Are there any practical reasons to use `-include` in a Makefile?

我最近在调试一个模糊的问题,该问题原来是由错误放置的子 Makefile 引起的,该子 Makefile 被 -include 指令 有条件地 包含到主 Makefile 中.注意起始减号。根据 GNU Make manual:

If you want make to simply ignore a makefile which does not exist or cannot be remade, with no error message, use the -include directive instead of include, like this:

-include filenames…

This acts like include in every way except that there is no error (not even a warning) if any of the filenames (or any prerequisites of any of the filenames) do not exist or cannot be remade.

For compatibility with some other make implementations, sinclude is another name for -include.

此指令最严重的问题是当找不到子 Makefile 时,不会给出任何诊断。不用说,这会使调试变得非常复杂。

事实上,没有真正需要在那里使用它,常规 include 工作得很好,而且更健壮。我理解原作者使用-include的用意。该子 Makefile 包含一些 "secret" 不应与第 3 方工程师共享的内容。但是这个功能最终没有用到,本来可以用更透明的方式实现的。

不知道还有没有其他实际案例可以用到-include。也许某些情况下在构建过程中会动态生成一个或多个 makefile?

当然,-include 最有用的应用是当包含文件由 make 本身 auto-generated 时。

请记住,所有包含文件也会自动成为 make 的目标。所以 -include generated_file 不会使 make 过早失败,但暗示 generated_file 将使用当前 Makefile 中的其他规则(重新)构建。例如,这可以在 auto-dependencies 代中被利用。

顺便说一句。 'include' 的另一个技巧是 include $(empty_var) 也可以正常工作(即 no-op)。