使用标头编译不同的.cpp文件

use*_*194 0 c++ g++ header

我有一个问题我试图使用GNU g ++一起编译多个文件

我们假设有五个文件:

main.cpp : the main function 
a.h      : the header file of class A 
a.cpp    : the definition of class A 
b.h      : the header file of class B 
b.cpp    : the definition of class B 
Run Code Online (Sandbox Code Playgroud)

在程序中,main.cpp使用类A(因此包括啊),类A使用类B(因此包括bh).

所以在我的主要内容中我刚刚添加了#include"啊"

我正在尝试使用它来编译它

g++ main.cpp -o main
Run Code Online (Sandbox Code Playgroud)

但这不起作用.它给了我一个"未定义的引用"错误.当我将所有类与头文件一起编译时,程序为我提供了所需的输出

有人可以告诉我哪里出错了

Car*_*rum 6

You need to compile all of the source files:

g++ main.cpp a.cpp b.cpp -o main
Run Code Online (Sandbox Code Playgroud)

If you want to do it in steps, you can do that too:

g++ -c main.cpp -o main.o  # compile
g++ -c a.cpp -o a.o        # compile
g++ -c b.cpp -o b.o        # compile
g++ -o main main.o a.o b.o # link
Run Code Online (Sandbox Code Playgroud)

But what you should be doing is using a proper makefile:

CXXFLAGS = -MMD
OBJECTS = main.o a.o b.o
MAKEDEPS = $(OBJECTS:.o=.d)

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

clean:
    rm -f *.d *.o main

.PHONY: clean

-include $(MAKEDEPS)
Run Code Online (Sandbox Code Playgroud)

Example:

$ make
c++ -MMD   -c -o main.o main.cpp
c++ -MMD   -c -o a.o a.cpp
c++ -MMD   -c -o b.o b.cpp
c++ -MMD -o main main.o a.o b.o
Run Code Online (Sandbox Code Playgroud)