我在C ++中编写了一个非常简单的类,即它是来自http://www.cplusplus.com/doc/tutorial/classes/的Rectangle类。特别是这里是Header文件(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;
}
现在,我应该在我的主类中包含矩形标题,即:
#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)
答案 0 :(得分:13)
您没有编译和链接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都是如此。
答案 1 :(得分:2)
不,您不应该包含.cpp
。你必须编译它,这应该产生一个.o
文件,然后链接到主可执行文件。无论出于何种原因,您的主管都无法找到并链接到此.o
文件。如果不知道你正在采取的确切编译和链接步骤,很难说更多。
答案 2 :(得分:0)
通常.h文件是类定义,所以你是对的。我不认为你在编译器选项中包含了“Rectangle.h”。