Helo,我正在尝试使用g ++在Ubuntu中编译我的c ++代码。
我有3个文件:Ball.h Ball.cpp main.cpp
头文件Ball.h
#ifdef BALL_H_
#define BALL_H_
class Ball {
public:
Ball();
Ball(int radius);
~Ball();
void setRadius(int);
int getRadius();
private:
int radius;
};
#endif //BALL_H_
Ball.cpp文件
#include "Ball.h"
Ball::Ball() {
radius = 1;
}
Ball::Ball(int rad) {
radius = rad;
}
Ball::~Ball() {
}
void Ball::setRadius(int rad) {
radius = rad;
}
int Ball::getRadius() {
return radius;
}
main.cpp文件
#include <iostream>
#include "Ball.h"
using namespace std;
int main() {
//Ball b, b2, b3(2);
Ball b = Ball();
Ball b2 = Ball();
Ball b3 = Ball(2);
cout << "Initial radius: ";
<<b.getRadius() << endl;
b.setRadius(10);
cout << "New radius: "
<< b.getRadius() << endl;
cout << "Initial radius b2: "
<< b2.getRadius() << endl;
b2.setRadius(20);
cout << "b/b2"
<< b.getRadius() << "/"
<< b2.getRadius() << endl;
cout <<"b3 radius: "
<< b3.getRadius() << endl;
return 0;
}
当我试图编译所有这3个文件时,编译器甚至找不到在main.cpp中声明的Ball对象我正在使用makefile来编译这3个文件。
Makefile:
GPP=g++
GPPOPT=-std=c++11
OBJ=Ball main
all: $(OBJ)
Ball:
$(GPP) $(GPPOPT) -c Ball.cpp -o $@
main:
$(GPP) $(GPPOPT) main.cpp -o $@
clean:
-$(RM) $(OBJ)
Compilator消息:
m4r1us@ubuntu:~/Desktop/cpptest$ make
g++ -std=c++11 -c Ball.cpp -o Ball
Ball.cpp:3:2: error: ‘Ball’ does not name a type
Ball::Ball() {
^
Ball.cpp:9:2: error: ‘Ball’ does not name a type
Ball::Ball(int rad) {
^
Ball.cpp:15:2: error: ‘Ball’ does not name a type
Ball::~Ball() {
^
Ball.cpp:19:7: error: ‘Ball’ has not been declared
void Ball::setRadius(int rad) {
^
Ball.cpp: In function ‘void setRadius(int)’:
Ball.cpp:21:2: error: ‘radius’ was not declared in this scope
radius = rad;
^
Ball.cpp: At global scope:
Ball.cpp:25:6: error: ‘Ball’ has not been declared
int Ball::getRadius() {
^
Ball.cpp: In function ‘int getRadius()’:
Ball.cpp:27:9: error: ‘radius’ was not declared in this scope
return radius;
^
make: *** [Ball] Error 1
m4r1us@ubuntu:~/Desktop/cpptest$
我认为编译存在一些问题。我无法弄清楚我做错了什么。有什么提示吗?
谢谢。
答案 0 :(得分:3)
检查你的头部防护装置。如果#ifdef BALL_H_
,则#ifndef BALL_H_
为{{1}}。