0

I have my header file in which i have the "selection" as you can see it's public static member .

#ifndef SHAREDDATA_H_
#define SHAREDDATA_H_
#include "cocos2d.h"
#include "GameTrinkets.h"
using namespace std;

class SharedData{
    private:
    //...
    //Instance of the singleton
    static SharedData* m_mySingleton;

public:
    //Get instance of singleton
    static SharedData* sharedGameManager();
    static int selection;
};
#endif /* SHAREDDATA_H_ */

Where i try to get access is:

  • I tried setting the selection trough just the namespace as it seemed the correct way to do it
  • I tried by going trough the singleton instance but got unlucky

So the code where i try it

#include "GameScene.h"
#include "GameTrinkets.h"
#include "SharedData.h"
#include <time.h>

void GameScene::mainSpriteSelection(int selection){
    //1
    SharedData::selection=3;        
   //2 
   SharedData::sharedGameManager()->selection=selection;
}

The error i get is :

[armeabi] SharedLibrary : libcocos2dcpp.so jni/../../Classes/GameScene.cpp:41: error: undefined reference to 'SharedData::selection'

Iszlai Lehel
  • 233
  • 3
  • 11
  • possible duplicate of [C++ static member variable and its initialization](http://stackoverflow.com/questions/4547660/c-static-member-variable-and-its-initialization) – Theolodis Aug 02 '14 at 06:27

3 Answers3

0

The error messages tells you that you need to define static variable selection

define it in GameScene.cpp file

int GameScene::selection = 0;
billz
  • 44,644
  • 9
  • 83
  • 100
0

You have to define the static variable outside your class (in the .cpp) as

int SharedData::selection;

Minimal example:

#include <iostream>

using namespace std;

struct Foo
{
    static int member;
};

int Foo::member; // definition here



int main()
{
    cout << Foo::member << endl;
}

Otherwise you get a linker error.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

In C++, when you declare a variable to be static you have to redefine it in the implementation file before you can use the variable. For example,

//in the header file.    
class foo{  
  public:  
  static int bar;  
};

//in the implementation file  
int foo::bar // optional initialisation.  


 //in the main program 
 //header files  
 int main(){
 foo::bar = desired_initialisation_value; //no problem  
}  
Pradhan
  • 16,391
  • 3
  • 44
  • 59