C++头文件 - 要包含的内容

C++ Header Files - What to include

本文关键字:包含 文件 C++      更新时间:2023-10-16

我用C++写了一个非常简单的类,即它是 http://www.cplusplus.com/doc/tutorial/classes/的矩形类。特别是这是头文件(Rectangle.h)的内容:

#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
private:
    double m_x;
    double m_y;
public:
    Rectangle();
    Rectangle(double, double);
    void setXY(double, double);
    double getArea();
};
#endif

下面是实现(矩形.cpp):

#include "Rectangle.h"
Rectangle::Rectangle() {
    setXY(1, 1);
}
Rectangle::Rectangle(double x, double y) {
    setXY(x, y);
}
void Rectangle::setXY(double x, double y) {
    m_x = x;
    m_y = y;
}
double Rectangle::getArea(void) {
    return m_x * m_y;
}

现在,我应该在我的主类中包含矩形的标题,即:

#include <stdlib.h>
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main(void) {
    Rectangle a;
    cout << "Area : " << a.getArea() << "n";
    return EXIT_SUCCESS;
}

但是,然后我得到错误:

make all 
g++ -O2 -g -Wall -fmessage-length=0   -c -o Chung1.o Chung1.cpp
g++ -o Chung1 Chung1.o 
Chung1.o: In function `main':
/home/chung/eclipse_ws/Chung1/Chung1.cpp:8: undefined reference to `Rectangle::Rectangle()'
/home/chung/eclipse_ws/Chung1/Chung1.cpp:9: undefined reference to `Rectangle::getArea()'
collect2: ld returned 1 exit status
make: *** [Chung1] Error 1

如果我包含文件矩形.cpp则错误得到解决。(我在Eclipse上运行)

毕竟我应该包含 CPP 文件吗?

这是我的制作文件:

CXXFLAGS =  -O2 -g -Wall -fmessage-length=0    
OBJS =      Chung1.o    
LIBS =    
TARGET =    Chung1    
$(TARGET):  $(OBJS)
    $(CXX) -o $(TARGET) $(OBJS) $(LIBS)    
all:    $(TARGET)    
clean:
    rm -f $(OBJS) $(TARGET)    
run:    $(TARGET)   
        ./$(TARGET)

如何修改它以编译矩形类?

解决方案:根据用户 v154c1 的回答,有必要编译单个 cpp 文件,然后将其标头包含在主文件或需要此功能的任何其他文件中。以下是执行此操作的任何示例 Makefile:

CXXFLAGS =      -O2 -g -Wall -fmessage-length=0
#List of dependencies...
OBJS =          Rectangle.o Chung1.o
LIBS =
TARGET =        Chung1
$(TARGET):      $(OBJS)
        $(CXX) -o $(TARGET) $(OBJS) $(LIBS)
all:    $(TARGET)
clean:
        rm -f $(OBJS) $(TARGET)
run:    $(TARGET)
        ./$(TARGET)

您没有编译和链接 Rectangle 类。

您的编译应如下所示:

g++ -O2 -g -Wall -fmessage-length=0   -c -o Chung1.o Chung1.cpp
g++ -O2 -g -Wall -fmessage-length=0   -c -o Rectangle.o Rectangle.cpp
g++ -o Chung1 Chung1.o Rectangle.o

如果您使用的是 Makefile,则只需添加矩形.cpp就像使用 Chung1.cpp 一样。您可能正在使用的任何 IDE 也是如此。

不,您不应该包含.cpp。您必须编译它,这应该生成一个.o文件,然后将其链接到主可执行文件。无论出于何种原因,您的主要原因是无法找到并链接到此.o文件。如果不知道您正在采取的确切编译和链接步骤,就很难说更多。

通常.h文件是类定义,所以你是对的。我不认为您在编译器选项中包含"Rectangle.h"。

相关文章: