问题描述
我是新来的,所以希望您能帮助我.我正在一个C ++项目中,尝试使用终端机(Mac Os)进行编译,但是当包含类的.hpp时,我总是会报错,但是当包含.cpp
I am new here, so I hope you can help me guys. I'm working in a C++ project, trying to compile it with terminal (Mac Os), but I always get an error when I include the .hpp of my class, but not when I include the .cpp
这些是我的文件:
main.cpp
#include "Point.hpp"
int main(){
Point p1;
}
Point.hpp
#ifndef Point_hpp
#define Point_hpp
#include <math.h>
#include <iostream>
#include <stdio.h>
class Point{
private:
double dX;
double dY;
public:
Point();
Point(double dX, double dY);
void setX(double dX);
double getX();
void setY(double dY);
double getY();
double getDistance(Point p);
void move(double dDespX, double dDespY);
void display();
};
#endif
Point.cpp
#include "Point.hpp"
Point::Point(){
dX = 0;
dY = 0;
}
Point::Point(double dX, double dY){
this -> dX = dX;
this -> dY = dY;
}
void Point::setX(double dX){
this -> dX = dX;
}
double Point::getX(){
return dX;
}
void Point::setY(double dY){
this -> dY = dY;
}
double Point::getY(){
return dY;
}
double Point::getDistance(Point p){
double dDist;
dDist = sqrt(pow(p.dX - dX, 2) + pow(p.dY - dY, 2));
return dDist;
}
void Point::move(double dDespX, double dDespY){
dX += dDespX;
dY += dDespY;
}
void Point::display(){
std::cout << "Point = (" << dX << "," << dY <<")" << std::endl;
}
当我尝试编译(使用'make main')时,我是从终端获取的:
When I try to compile (using 'make main') I am getting this from terminal:
$ make main
c++ main.cpp -o main
Undefined symbols for architecture x86_64:
"Point::Point()", referenced from:
_main in ccVzh5gg.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [main] Error 1
推荐答案
您需要将Point.cpp
添加到要编译的文件列表中,并链接到makefile中.因此将编译行更改为
You need to add Point.cpp
to the list of files you compile and link in the makefile. So change the compile line to
c++ main.cpp Point.cpp -o main
由于您没有将Point.cpp
文件中的定义链接到可执行文件,因此您无法访问Point.cpp
中提供的函数,因此您仅在编译时知道它们的声明(参数和返回值).
Because you don't link the definitions from the Point.cpp
file to the executable you don't have access to the functions provided in Point.cpp
you only know their declarations (parameters and return values) at compile time.
这篇关于gcc 4.7.4链接问题:体系结构x86_64的未定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!