内容简介:http://stackoverflow.com/questions/13441822/c-header-files-what-to-include
的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头文件 – 包含什么[已关闭]》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Impractical Python Projects
Lee Vaughan / No Starch Press / 2018-11 / USD 29.95
Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!
在线进制转换器
各进制数互转换器
HEX CMYK 转换工具
HEX CMYK 互转工具