C++ - Makefile 良好实践

标签 c++ makefile g++

我有一个适用于我如何使用它的 Makefile,但是有人会告诉我我正在做的事情是否是好的做法吗?或者是否有更好、更清洁或更有效的方法来实现我正在达到的目标?

这是我的 Makefile 代码。

# Object files to either reference or create
OBJECTS = Proj2.o Blackjack.o Deck.o Card.o Hand.o Player.o
# The executable file that will be created
EXEC = Proj2.out
# The c++ flags to use for compilation
CXXFLAGS = -Wall
# The c++ compiler to use for compilation
CXX = g++

# This section is called on 'make'
# Will call compile, and then call clean
all: compile clean

# Perform action on all object files (May or may not exist)
# The makefile will implicitly compile all .o files needed
# Will also compile them into the EXEC file listed
compile: $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $(EXEC) $(OBJECTS)

# This section is called after compilation is completed
# This will clean all existing .o files listed in the directory
clean:
    rm -f *.o

这是我调用 make 时的终端输出。

g++ -Wall   -c -o Proj2.o Proj2.cpp
g++ -Wall   -c -o Blackjack.o Blackjack.cpp
g++ -Wall   -c -o Deck.o Deck.cpp
g++ -Wall   -c -o Card.o Card.cpp
g++ -Wall   -c -o Hand.o Hand.cpp
g++ -Wall   -c -o Player.o Player.cpp
g++ -Wall -o Proj2.out Proj2.o Blackjack.o Deck.o Card.o Hand.o Player.o
rm -f *.o

像这样使用 Makefile 是好的做法吗?具体来说,我是否正确地执行了 Makefile 的清理部分?

最佳答案

你根本不应该让 all 依赖于 clean。通过这样做,您可以确保每次运行 make 时,您都必须重新编译所有内容。如果你想这样做,那么使用 make 本身是没有用的:只需编写一个 shell 脚本来编译和链接你的代码。

clean 目标应该是一个单独的目标,如果你想清理你的工作区,你可以明确地运行 make clean

您的 makefile 的另一个问题是链接规则将 compile 列为目标,但它构建了 $(EXE)。让规则创建一个与您告诉 make 它将构建的目标不完全相同的文件几乎不是一个好主意。为确保这一点,请始终使用 $@ 作为要生成的目标。像这样重写:

compile: $(EXE)

$(EXE): $(OBJECTS)
        $(CXX) $(CXXFLAGS) -o $@ $^

关于C++ - Makefile 良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22570320/

相关文章:

c++ - 生成所有汉明距离至多为2的无序位串对

java - 从 QBytearray 创建 QImage

makefile - Makerule 只运行一个规则

c++ - 对于 c++ 的 makefile 来说,一切都是明确的吗?

xcode - CMake:如何在 *nix 系统上使用所有内核构建外部项目?

c++ - Qt C++ 迭代时修改列表中的对象

在 Windows 中编译的 C++ 程序产生不同的输出

c++ - 模板参数类型成员上的运算符 << 仅在 clang 中导致错误

path - 如何在 g++ 中包含库的路径

c++ - 如何从g++中的链接库中删除路径