Makefile 简明教程

Defining Dependencies in Makefile

最终二进制文件依赖于各种源代码和源头文件是非常常见的。依赖关系很重要,因为它们允许 make 知道任何目标的源代码。考虑以下示例 −

It is very common that a final binary will be dependent on various source code and source header files. Dependencies are important because they let the make Known about the source for any target. Consider the following example −

hello: main.o factorial.o hello.o
   $(CC) main.o factorial.o hello.o -o hello

在这里,我们告诉 make hello 依赖于 main.o、factorial.o 和 hello.o 文件。因此,每当这些目标文件中的任何一个发生更改时, make 都会采取措施。

Here, we tell the make that hello is dependent on main.o, factorial.o, and hello.o files. Hence, whenever there is a change in any of these object files, make will take action.

同时,我们需要告诉 make 如何准备 .o 文件。因此,我们还需要定义这些依赖项,如下所示 −

At the same time, we need to tell the make how to prepare .o files. Hence we need to define those dependencies also as follows −

main.o: main.cpp functions.h
   $(CC) -c main.cpp

factorial.o: factorial.cpp functions.h
   $(CC) -c factorial.cpp

hello.o: hello.cpp functions.h
   $(CC) -c hello.cpp