内容简介:http://stackoverflow.com/questions/13441822/c-header-files-what-to-include
我在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;
}
现在我应该把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也是如此.
http://stackoverflow.com/questions/13441822/c-header-files-what-to-include
以上所述就是小编给大家介绍的《C头文件 – 包含什么[已关闭]》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Android获取软键盘的高度、键盘的打开与关闭、监听键盘处于打开还是关闭状态
- 关于python关闭
- Swift关闭UITextView键盘
- Android 书本打开和关闭动画
- CentOS 7 关闭透明大页
- Oracle数据库启动和关闭
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。