如何使用单个makefile编译不同目录下的多个.cpp文件

How to do makefile to compile multiple .cpp files in different directories using a single makefile?

本文关键字:文件 cpp 单个 何使用 makefile 编译      更新时间:2023-10-16

我的proj2目录中有以下文件,需要将它们编译成一个可执行文件。

    proj2/main.cpp
    proj2/model/Player.cpp
    proj2/model/gameBoard.cpp
    proj2/controller/TTTController.cpp
    proj2/Makefile

我在我的makefile中使用了以下命令,但是它不起作用。

all:
    g++ /project2_p1/main.cpp /project2_p1/controller/TTTController.cpp          /model/gameBoard.cpp /model/Player.cpp -o ttt
clean:
    -rm ttt
有谁能帮帮我吗?谢谢你

我强烈建议您开始学习make,因为它是程序员使用的基本工具之一。而且,如果你能学会C++,你一定能学会make

在你的项目中,你有源文件埋在自己的子目录中,所以为了找到它们,你可以使用$(shell find...)命令。与项目中的任何头文件相同。

通过使all:成为直接目标,它将无条件执行,并且您将失去使用make的好处-仅在更改某些内容时进行编译。

我已经说过,我在这里提供的基本模板可以改进,只重新编译那些已更改的源文件,但这是读者的练习。

我认为这应该适用于你的情况:

# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors
# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS += 
# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
# find headers
HEADERS := $(shell find . -name '*.h')
OUTPUT := ttt
# Everything depends on the output
all: $(OUTPUT)
# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)
clean:
    $(RM) $(OUTPUT)

这是我的minGW项目的makefile代码:

hepsi: derle calistir
Nesneler :=  ./lib/Hata.o ./lib/Hatalar.o ./lib/Dugum.o ./lib/ListeGezici.o ./lib/BagilListe.o
    derle:
        g++ -I ./include/ -o ./lib/Hata.o -c ./src/Hata.cpp
        g++ -I ./include/ -o ./lib/Hatalar.o -c ./src/Hatalar.cpp
        g++ -I ./include/ -o ./lib/Dugum.o -c ./src/Dugum.cpp
        g++ -I ./include/ -o ./lib/ListeGezici.o -c ./src/ListeGezici.cpp
        g++ -I ./include/ -o ./lib/BagilListe.o -c ./src/BagilListe.cpp
        g++ -I ./include/ -o ./bin/test $(Nesneler) ./src/test.cpp
    calistir:
        ./bin/test

在你的项目中,我认为这将工作;

    all: compile run
Objects :=  ./lib/Player.o ./lib/gameBoard.o ./lib/TTTController.o 
compile:
    g++ -I ./include/ -o ./lib/Player.o -c ./model/Player.cpp
    g++ -I ./include/ -o ./lib/gameBoard.o -c ./model/gameBoard.cpp
    g++ -I ./include/ -o ./lib/TTTController.o -c .controller/TTTController.cpp
    g++ -I ./include/ -o ./bin/main $(Objects) ./main.cpp
run:
    ./bin/main

lib文件夹包含。o文件。如果你愿意,你可以试试。include文件夹指的是头文件.h.hpp。你可以根据你的头文件的位置来改变它们中的每一个。

bin文件夹包含.exe文件,称为main.exe。你可以像这样修改或删除

run: 
   ./main

我希望它能起作用。

@Galik有权利。如果你想学习C++,你一定要学习make