2013-11-15 4 views
4

Я работаю над изучением ООП с C++ и с проблемой. Я уверен, что проблема с распределением памяти, но, похоже, не имеет головы вокруг нее. Любая помощь будет оценена.undefined ссылка на std :: ios_base :: Init :: Init()

Мой код клиента

#include <iostream> 
    #include "Box.cpp" 

    using namespace std; 

    int main(){ 
     Box *box = new Box; 
     return 0; 
    } 

My Box Class ...

#include <iostream> 

    using namespace std; 

    class Box{ 

     private: 
      double width; 
      double height; 
      double perimeter; 
      double area; 


     public: 
      Box(){ 
       cout << "Box created" << endl; 
      } 

      ~Box(){ 
       cout << "Box Destroyed" << endl; 
      } 

      double getWidth(){ 
       // 
       return this->width; 
      } 

      double getHeight(){ 
       // 
       return this->height; 
      } 

      double getArea(){ 
       // 
       return this->area; 
      } 

      double getPerimeter(){ 
       // 
       return this->perimeter; 
      } 

      void setWidth(double w){ 
       // 
       this->width = w; 
       if(!this->height){ 
        computeSetArea(this->width, this->height); 
        computeSetPerimeter(this->width, this->height); 
       } 
      } 

      void setHeight(double h){ 
       // 
       this->height = h; 
       if(!this->width){ 
        computeSetArea(this->width, this->height); 
        computeSetPerimeter(this->width, this->height); 
       } 
      } 

     private: 
      void computeSetArea(double w, double h){ 
       // 
       this->area = w*h; 
      } 

      void computeSetPerimeter(double w, double h){ 
       // 
       this->perimeter = (w * 2) + (h + 2); 
      } 
    }; 

Я использую GCC и выполнить:

gcc Box.cpp client.cpp -o mainfile 

После такого я получаю эту ошибку.

/tmp/ccaVb21k.o: In function `__static_initialization_and_destruction_0(int, int)': 
Box.cpp:(.text+0x1d): undefined reference to `std::ios_base::Init::Init()' 
Box.cpp:(.text+0x22): undefined reference to `std::ios_base::Init::~Init()' 
/tmp/ccaVb21k.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' 
/tmp/ccjtbzi4.o: In function `main': 
client.cpp:(.text+0x14): undefined reference to `operator new(unsigned int)' 
client.cpp:(.text+0x3f): undefined reference to `operator delete(void*)' 
/tmp/ccjtbzi4.o: In function `__static_initialization_and_destruction_0(int, int)': 
client.cpp:(.text+0x6c): undefined reference to `std::ios_base::Init::Init()' 
client.cpp:(.text+0x71): undefined reference to `std::ios_base::Init::~Init()' 
/tmp/ccjtbzi4.o: In function `Box::Box()': 
client.cpp:(.text._ZN3BoxC1Ev[Box::Box()]+0x11): undefined reference to `std::cout' 
client.cpp:(.text._ZN3BoxC1Ev[Box::Box()]+0x16): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' 
client.cpp:(.text._ZN3BoxC1Ev[Box::Box()]+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' 
client.cpp:(.text._ZN3BoxC1Ev[Box::Box()]+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))' 
/tmp/ccjtbzi4.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' 
/tmp/ccjtbzi4.o:(.eh_frame+0x4b): undefined reference to `__gxx_personality_v0' 
collect2: ld returned 1 exit status 
+0

, пожалуйста, посмотрите здесь: http://stackoverflow.com/q uestions/1696300/how-to-compile-c-under-ubuntu-linux? rq = 1 – rsc

+0

По соглашению .h файлы содержат определение класса, в то время как .cpp-файлы содержат реализацию класса, поэтому вы должны: либо разделить определение в .h-файл и сохранить реализацию в cpp или переименовать ваш .cpp в .h (так как это действительно .h с встроенной реализацией). Если вы * сделаете * переименовать файл в .h, удалите использование пространства имен std; из файла .h, так как это плохая практика, чтобы загрязнять глобальное пространство имен внутри файла заголовка. – Alan

ответ

8

Ваш код компилируется нормально, вы получаете сообщение об ошибке компоновщика (ld является линкер, и это возвращение 1 (ошибка)), который жалуется на отсутствие C++ LIBS.

Чтобы исправить это, вам нужно добавить stdC++ lib в свою командную строку или использовать g ++.

Замените gcc на g++ или добавьте -lstdc++ в вашу командную строку gcc.

gcc Box.cpp client.cpp -o mainfile -lstdc++

или

g++ Box.cpp client.cpp -o mainfile

Это позволит связать станд C++ библиотеку с скомпилированного кода. Используя g++, вы можете опустить этот шаг.

1

Настройка вашей классовой структуры, как это работает для меня:

Box.h:

class Box 
{ 
public: 
    Box(); 
    ~Box(); 

    double getWidth(); 
    double getHeight(); 
    double getArea(); 
    double getPerimeter(); 
    void setWidth(double w); 
    void setHeight(double h); 
    void computeSetArea(double w, double h); 
    void computeSetPerimeter(double w, double h); 

private: 
    double width; 
    double height; 
    double perimeter; 
    double area; 
}; 

А потом Box.cpp:

#include "box.h" 
#include <iostream> 
using namespace std; 

Box::Box(){ 
    cout << "Box created" << endl; 
} 

Box::~Box(){ 
    cout << "Box Destroyed" << endl; 
} 

double Box::getWidth(){ 
    return this->width; 
} 

double Box::getHeight(){ 
    return this->height; 
} 

double Box::getArea(){ 
    return this->area; 
} 

double Box::getPerimeter(){ 
    return this->perimeter; 
} 

void Box::setWidth(double w){ 
    this->width = w; 
    if(!this->height){ 
     computeSetArea(this->width, this->height); 
     computeSetPerimeter(this->width, this->height); 
    } 
} 

void Box::setHeight(double h){ 
    this->height = h; 
    if(!this->width){ 
     computeSetArea(this->width, this->height); 
     computeSetPerimeter(this->width, this->height); 
    } 
} 

void Box::computeSetArea(double w, double h){ 
    this->area = w*h; 
} 

void Box::computeSetPerimeter(double w, double h) { 
    this->perimeter = (w * 2) + (h + 2); 
} 

Выход:

Box created 
+0

Должен ли я компилироваться с исходным файлом файла заголовка или просто с заголовком? – seanr

+0

Просто исходные файлы, никогда не скомпилируйте заголовки напрямую. Также никогда не включайте один исходный файл в другой (например, ваш код выше). – john

+0

@seanr, Привет, Шон, да, точно так же, как говорит Джон. Я использовал: «g ++ Box.cpp main.cpp -o mainfile», а затем, конечно, я использовал: «./mainfile» Это работало для вас? –

Смежные вопросы