C++ 头文件 - 包含什么

标签 c++ compilation header-files

我用 C++ 编写了一个非常简单的类,即 http://www.cplusplus.com/doc/tutorial/classes/ 中的 Rectangle 类。 .特别是这里的头文件(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

这里是实现(Rectangle.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;
}

现在,我应该在我的主类中包含 Rectangle 的 Header,即:

#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

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

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

这是我的 Makefile:

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)

如何修改它以编译 Rectangle 类?

解决方案:根据用户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,那么只需像使用 Chung1.cpp 一样添加 Rectangle.cpp。您可能正在使用的任何 IDE 也是如此。

关于C++ 头文件 - 包含什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441822/

相关文章:

安卓工作室 : Are language xml files compiled into the apk?

java - 了解如何使用 Jython 的问题

java - 编译时如何通配符包含 JAR 文件?

c++ Xcode 预期 '(' 用于函数样式转换或类型构造

c++ - 进程在内存/Win32 调试 API 中的真实起始地址

c++ - c++ if语句中的多个条件(通过链表的堆栈实现)

c - 如何将每个字符一一打印出来?

c - 不存在的目录中的多个定义

c++ - 引用 Qt C++ Project 中包含的库

c++ - 复制位模式: float 到uint32_t