当隐式规则没有说明可执行文件时,make 如何从 C 源文件构建可执行文件?

How does make build an executable file from a C source file when the implicit rule says nothing about executables?

GNU Make Manual 我了解到 .c 程序有一个隐含规则:

n.o is made automatically from n.c with a recipe of the form ‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’

例如,当我键入 make helloworld 并且我的工作目录中只有一个 helloworld.c 文件时,我看到执行了以下命令:

cc helloworld.c -o helloworld

如果我键入 make -d helloworld,我会发现 make 绝不会查找中间 helloworld.o 文件。

最后,我在我的目录中没有看到 .o 文件,只有可执行文件。如果 .c 程序的隐式规则说它应该构建一个 .o 文件,make 如何从源文件构建可执行文件?

内置数据库中有不同的隐式规则。如果模式规则不明确,make 永远不会反对,因为它总是为它们设置优先级。

在这种情况下,规则 %: %.o%.o: %.c 被规则 %: %.c 取代(因为一步比两步好 ;-)),它编译成一个无需创建目标文件即可执行(是的,gcc 可以做到这一点)。

但是,您可以使用此命令强制创建 .o:

make helloworld.o helloworld

在这里,helloworld.o创建成功后,make会优先%: %.o规则而不是%: %.c,所以它按预期工作。

有很多隐含的规则。在这种情况下,有一个用于直接从 C 文件构建可执行文件。在 make -d helloworld 的输出中,您应该看到如下内容:

Trying implicit prerequisite 'helloworld.c'.

Found an implicit rule for 'helloworld'.