gpt4 book ai didi

c++ - 更好地理解 makefile - 在这种情况下如何生成 .o 文件

转载 作者:行者123 更新时间:2023-11-27 23:02:11 28 4
gpt4 key购买 nike

我目前有以下生成文件(我正在使用在线教程的示例),但我对此有几个问题:

# *****************************************************
# Variables to control Makefile operation

CXX = g++
CXXFLAGS = -Wall -g


test: main.o car.o student.o house.o
$(CXX) $(CXXFLAGS) -o test main.o car.o student.o house.o
objcopy --only-keep-debug test test.debug

main.o: student.h house.h main.cpp
$(CXX) $(CXXFLAGS) -c main.cpp

car.o: car.h

student.o: student.h car.h

house.o: house.h

clean:
rm -rf *.o test *.debug

这是我对这里发生的事情的理解,如果我错了请纠正我。当调用 initially 测试目标时,它会查找第一个依赖项 main.o 这可以是文件或目标。由于没有名为 main.o 的文件,它将寻找 main.o 作为目标。一旦找到 main.o 作为目标,它就会查找依赖项 student.h house.h main.cpp 因为它们作为文件存在 make 然后执行配方(命令),即 $( CXX) $(CXXFLAGS) -c main.cpp.现在这是我不明白的部分。当第二个依赖项 car.o 轮到时,make 查找 car.h 并找到它,但没有命令告诉它生成 .o 文件。 .o 文件是如何在这里生成的?

最佳答案

make 包含几个隐式规则。这意味着 make 具有关于如何从 .cpp 文件创建 .o 文件的内置知识,而无需您明确告诉它如何去做。

来自文档:

Compiling C++ programs

n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form ‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’. We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’

你可能认为这是 make 有一个看起来很像的内置规则:

%.o : %.cpp
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@

阅读有关这些隐式规则的更多信息 herehere .

关于c++ - 更好地理解 makefile - 在这种情况下如何生成 .o 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26664541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com