0

I just installed MinGW and Eclipse and tried to program a very simple Demo, I jst used the Project for Building an executable and added two files for a Class. It acturally generates two objects, text.o(the function with main) and the MyClass.o. But I get the Error, there seems something wrong with the linking I guess:

12:23:24 **** Incremental Build of configuration Debug for project test **** Info: Internal Builder is used for build

g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\MyClass.o" "..\src\MyClass.cpp"

g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\test.o" "..\src\test.cpp"

g++ -o test.exe "src\test.o" "src\MyClass.o"

src\MyClass.o:MyClass.cpp:(.rdata$.refptr._ZN7myClass13myInternalVarE[.refptr._ZN7myClass13myInternalVarE]+0x0): undefined reference to `myClass::myInternalVar'

collect2.exe: error: ld returned 1 exit status

MyClass Headerfile:

#ifndef MYCLASS_HPP_
#define MYCLASS_HPP_

class myClass{

private:

  static int myInternalVar;

protected:

public:

  myClass();

  myClass(int initVal);

  ~myClass();

  void set(int value);

  int get();

};

#endif /* MYCLASS_HPP_ */

MyClass Sourcefile:

#include "MyClass.hpp"


  myClass::myClass()
  {

  }

  myClass::myClass(int initVal)
  {

  }

  myClass::~myClass()
  {

  }

  void myClass::set(int value)
  {
    myClass::myInternalVar = value;
  }

  int myClass::get()
  {
    return myClass::myInternalVar;
  }

Test Source:

using namespace std;
#include <iostream>
#include "MyClass.hpp"


int main() {
    myClass* myClass_object = new myClass( 33 );
  int i = 0;
  cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

  i = myClass_object->get();

  cout << "Value is: " << i << endl;

    return 0;
}

I tried to find a solution; I don't think it's the Code that's wrong, but the setting within eclipse. Can anyone help, I just started programming with MinGW and eclipse and it's frustrating that such an easy example fails.

Thank you very much,

Sebastian

codeling
  • 11,056
  • 4
  • 42
  • 71
SebWen
  • 1
  • See here: http://stackoverflow.com/questions/272900/undefined-reference-to-static-class-member. Basically you need to define (and possibly initialize) your static class member somewhere in your cpp, like this: `int myClass::myInternalVar = 0;` – codeling Dec 18 '15 at 11:58
  • Hello codeling, could you please post the code? I tried many different things on your recommendation which all failed. Thank you very much, Best Regards, Sebastian – SebWen Dec 18 '15 at 14:38
  • Ok, I guess I found the Pronlem, it was the static, but why? What's the reason behind that(technically) ? Thank you very much, Best Regards, Sebastian – SebWen Dec 18 '15 at 14:55
  • did you take a look at the linked question? There they explain it quite nicely – codeling Dec 20 '15 at 16:11
  • I think the Issue can be closed, a good explaination is here: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/ Thank you for the help. – SebWen Dec 21 '15 at 17:19

0 Answers0