Pan*_*kis 16 c++ compilation header-files
我在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
Run Code Online (Sandbox Code Playgroud)
这是实现(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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我应该在我的主类中包含矩形标题,即:
#include <stdlib.h>
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main(void) {
Rectangle a;
cout << "Area : " << a.getArea() << "\n";
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
但是,然后我得到错误:
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
Run Code Online (Sandbox Code Playgroud)
如果我包含文件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)
Run Code Online (Sandbox Code Playgroud)
如何修改它以编译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)
Run Code Online (Sandbox Code Playgroud)
v15*_*4c1 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
Run Code Online (Sandbox Code Playgroud)
如果您正在使用Makefile,那么只需添加Rectangle.cpp,就像使用Chung1.cpp一样.您可能正在使用的任何IDE都是如此.