我有一个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的清洁部分吗?
答案 0 :(得分:2)
您根本不应该依赖all
clean
。通过这样做,您确保每次运行make
时,都必须重新编译所有内容。如果你想这样做,那么使用make
本身就没用了:只需编写一个shell脚本来编译和链接你的代码。
clean
目标应该是一个单独的目标,如果要清理工作区,请明确运行make clean
。
makefile的另一个问题是链接规则将compile
列为目标,但它构建$(EXE)
。让一个规则创建一个文件并不是一个好主意,这个文件并不完全是你所建议的目标。为确保这一点,请始终使用$@
作为生成目标。像这样改写:
compile: $(EXE)
$(EXE): $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $@ $^