C++ - 编译多个文件

C++ - Compiling multiple files

我正在学习似乎非常强大的 makefile 工具,并试图弄清楚如何让它工作,因为我有 4 个不同的主电源和一个用于其中 3 个的公共 class。

我想得到的是:

线性:g++ -o linear linear.cpp

线性 5:g++ -o linear5 linear5.cpp Contenidor.cpp Contenidor.h

对数:g++ -o logarithmic logarithmic.cpp Contenidor.cpp Contenidor.h

常量:g++ -o constant constant.cpp Contenidor.cpp Contenidor.h

使用以下 Makefile 代码:

all: linear5 linear logarithmic constant

linear5: linear5.o
    g++ -o linear5 linear5.o

linear5.o: linear5.cpp
    g++ -cpp linear5.cpp

Contenidor.o: Contenidor.cpp
    g++ -cpp Contenidor.cpp

linear: linear.o Contenidor.o
    g++ -o linear linear.o Contenidor.o

linear.o: linear.cpp
    g++ -cpp linear.cpp

logarithmic: logarithmic.o Contenidor.o
    g++ -o logarithmic logarithmic.o Contenidor.o

logarithmic.o: logarithmic.cpp
    g++ -cpp logarithmic.cpp

constant: constant.o Contenidor.o
    g++ -std=gnu++0x -o constant constant.o Contenidor.o

constant.o: constant.cpp
    g++ -cpp constant.cpp

clean:
    rm *.o

但是当我尝试执行 make 命令时出现错误:

g++ -cpp linear5.cpp
g++ -o linear5 linear5.o
g++: linear5.o: No such file or directory
g++: no input files

问题在于您执行两步编译的方式:您应该更改

的每个实例
file.o: file.cpp
    g++ -cpp file.cpp

进入:

file.o: file.cpp
    g++ -c -o file.o file.cpp

这样,您告诉 g++ 只编译 (-c) 而不是 link 您的文件;输出将是一个目标文件,但您仍然必须使用 -o 指定其名称。

然后,目标文件可以在后面的步骤中使用。