c++ - 正确的 makefile 依赖列表 (C++)

标签 c++ makefile

关于哪些文件被视为 main.o 的依赖项,我看到的很多关于 make 文件的示例都有些不一致。我想知道创建 makefile 的最安全、最有效的方法是什么。

来自 https://www.tutorialspoint.com/makefile/makefile_quick_guide.htm 的示例:

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

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

如你所见,头文件functions.hmain.o 的依赖项.

我教科书中的一个例子:

myprog.exe : main.o threeintsfcts.o
    g++ main.o threeintsfcts.o -o myprog.exe

main.o : main.cpp threeintsfcts.cpp threeintsfcts.h
    g++ -Wall -c main.cpp 

threeintsfcts.o : threeintsfcts.cpp threeintsfcts.h
    g++ -Wall -c threeintsfcts.cpp 

clean :
    rm *.o myprog.exe

如你所见,头文件.h它是 .cppmain.o 的依赖项.

我还看到了另一个示例(来自 https://www.youtube.com/watch?v=_r7i5X0rXJk ),其中唯一的依赖项是 main.omain.cpp .

类似于:

myprog.exe : main.o threeintsfcts.o
        g++ main.o threeintsfcts.o -o myprog.exe

    main.o : main.cpp 
        g++ -Wall -c main.cpp 

    threeintsfcts.o : threeintsfcts.cpp threeintsfcts.h
        g++ -Wall -c threeintsfcts.cpp 

    clean :
        rm *.o myprog.exe

main.cpp包括 .h文件,应该是 .h及其各自的.cpp被包含为依赖项?

我脑海中浮现的一个想法是:为什么要 .h文件仍然作为依赖项包含在内吗?不会有任何变化 .h文件注册为相应的更改 .cpp文件自 .h 的内容将被复制并粘贴到相应的 .cpp 中通过#include 文件?

我也不确定是否有相应的 .cpp作为依赖。
(例如 main.o : main.cpp threeintsfcts.cpp threeintsfcts.h )。 我认为这样做会违背 makefile 的主要优点之一,即模块化编译的效率。 (只要 main 发生变化,您就必须重新编译 threeintsfcts.cpp

但是,如果threeintsfcts.cpp,这样做可能是有意义的更改其在 main 中使用的函数之一的名称你忘了在 main 中更改它.

最佳答案

显然,每个目标文件目标都需要依赖于它的源文件,但也需要依赖于它包含的所有头文件。 make 程序本身不解析源文件,因此它不知道源文件包含哪些头文件。如果其中一个头文件丢失并被修改,源文件将不会被 make 自动重新编译。

因为手动跟踪头文件依赖关系很麻烦而且容易出错,所以有一些工具可以自动化它,参见例如this question .

但是,其他源文件不应该是依赖项,因为一个源文件不应该包含另一个源文件,所以在主可执行目标的后续链接器步骤中,不可能有任何 Unresolved 依赖项。

如果一个源文件中的任何更改会影响另一个源文件编译步骤的更改,则必须通过更改包含在后一个源文件中的前一个源文件的头文件来实现。因此 header 依赖性就足够了。

因此,我认为您发布的教科书示例没有任何理由。然而,第一个示例很好,只要项目大小足够小以手动跟踪依赖项。第三个例子是错误的,因为如果头文件改变它不会重新编译main.cpp。 (假设 threeintsfcts.h 包含在 main.cpp 中,这是唯一有意义的东西)

关于c++ - 正确的 makefile 依赖列表 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57697345/

相关文章:

c++ - "vector"未在此范围内声明

同时为静态库和可执行文件创建 makefile

oracle - 在 makefile 中设置动态 ORACLE_HOME

c++ - 'using Base<T>::func( )' in derived class makes ' func' 在派生类之外无法访问

c++ - 函数模板推导中的类型转换

javascript - 检查对象属性是否更改其值

c++ - 为 Matrix 类设计迭代器

python - 编译程序使其独立于系统

c - 制作 : Nothing to be done for `all'

go - 特定目标的 Makefile 环境变量