如何让我的makefile更通用?

时间:2012-09-20 15:22:36

标签: makefile

我有一个makefile,当我需要添加另一个属于项目的文件时,我还需要进行大量编辑以使其全部工作。我想只编写一次我的makefile并完成它!所以,这是脚本:

CC=g++
CFLAGS=-c -Wall

#All paths start in the main directory which has this makefile, object/ and code/.
OBJPATH=object#All compiled .o files need to be placed here.
CODEPATH=code#All .cpp and .hpp header files reside here.

#The names of all the object files that need to be made.
OBJ=$(OBJPATH)/World.o $(OBJPATH)/Block.o $(OBJPATH)/Creep.o $(OBJPATH)/Food.o $(OBJPATH)/Brick.o

all : World.a


$(OBJPATH)/World.o : $(CODEPATH)/World.hpp $(CODEPATH)/World.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/World.cpp
    mv World.o $(OBJPATH)/

$(OBJPATH)/Block.o : $(CODEPATH)/Block.hpp $(CODEPATH)/Block.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/Block.cpp
    mv Block.o $(OBJPATH)/

$(OBJPATH)/Creep.o : $(CODEPATH)/Creep.hpp $(CODEPATH)/Creep.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/Creep.cpp
    mv Creep.o $(OBJPATH)/

$(OBJPATH)/Food.o : $(CODEPATH)/Food.hpp $(CODEPATH)/Food.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/Food.cpp
    mv Food.o $(OBJPATH)/

$(OBJPATH)/Brick.o : $(CODEPATH)/Brick.hpp $(CODEPATH)/Brick.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/Brick.cpp
    mv Brick.o $(OBJPATH)/


#This archive is the final result of the compilation:
World.a : $(OBJ)
    ar rvs World.a $(OBJ)
    cp $(CODEPATH)/World.hpp . #I need both the World.a file and the World.hpp file from code/ for this library to function.


#Delete all object files and the archive:
clean : 
    rm $(OBJPATH)/*.o World.a World.hpp *~ $(CODEPATH)/*~

#Delete all backup files made by Gedit:
pretty :
    rm *~ $(CODEPATH)/*~

这基本上做的是编译文件夹.o中的所有object/文件,然后将它们放在名为World.a的文件中。然后它只复制World.hpp,因为这是库的头文件。我相信很多代码都可以最小化,因此它更具可读性和通用性(每次创建新类时都不需要我编辑它)。

1 个答案:

答案 0 :(得分:2)

查看一个目标文件的规则:

$(OBJPATH)/World.o : $(CODEPATH)/World.hpp $(CODEPATH)/World.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/World.cpp
    mv World.o $(OBJPATH)/

让我们构建我们想要的对象,而不是使用mv

$(OBJPATH)/World.o : $(CODEPATH)/World.hpp $(CODEPATH)/World.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/World.cpp -o $(OBJPATH)/World.o

然后使用自动变量:

$(OBJPATH)/World.o : $(CODEPATH)/World.hpp $(CODEPATH)/World.cpp
    $(CC) $(CFLAGS) $(CODEPATH)/World.cpp -o $@

然后反转先决条件的顺序,以便我们可以使用另一个自动变量:

$(OBJPATH)/World.o : $(CODEPATH)/World.cpp $(CODEPATH)/World.hpp
    $(CC) $(CFLAGS) $< -o $@

现在命令没有按名称提及World,因此我们可以对所有对象使用相同的规则。为了使这个答案简短,我将首先将其作为静态模式规则:

$(OBJPATH)/World.o : $(OBJPATH)/%.o : $(CODEPATH)/%.cpp $(CODEPATH)/%.hpp
    $(CC) $(CFLAGS) $< -o $@

然后将它们全部合并:

OBJ=$(OBJPATH)/World.o $(OBJPATH)/Block.o $(OBJPATH)/Creep.o $(OBJPATH)/Food.o $(OBJPATH)/Brick.o

$(OBJ) : $(OBJPATH)/%.o : $(CODEPATH)/%.cpp $(CODEPATH)/%.hpp
    $(CC) $(CFLAGS) $< -o $@

现在,当您想要添加新文件时,您只需将其添加到OBJ=...行即可。你可以做一些改进,但这已经足够一天了。