Contents

昨天上课老师让我们写一个简单的头文件与源文件分离的C++面向对象编程,源码如下:

此工程在VS下可以运行,但在code::blocks下却一直报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "pt.h"
using namespace std;
int main()
{
Point pt;
pt.x = 3;
pt.y = 5;
pt.output();
return 0;
}
1
2
3
4
5
6
class Point {
public:
int x;
int y;
int output();
};
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "pt.h"
using namespace std;
int Point::output() {
cout << x << " " << y << endl;
return 0;
}

如上,问题就是出在Point::output这个函数上,经过我查找各种资料,我终于明白了是link的时候pt.cpp没有被包含在内,导致main函数找不到Point::output函数的定义,因此报错。

我又在网上查来查去,最后终于找到解决方法:

build targets

在工程上右键选择最后一项Properties(属性),点开Build targets选项卡,将下面的Build target files里的.cpp文件都勾上,就可以了。顺便我用的编译器是g++ 5.1.0。

Contents