weird problem with singleton with android

weird problem with singleton with android
0.0 0


I’m trying to write a singleton class for maintain game data, It’s called GameManager, just like the book .

here is my .h file:

#ifndef GameManager_h
#define GameManager_h

#include "cocos2d.h"

class GameManager

    //Instance of the singleton
    static GameManager* m_mySingleton;

    //Get instance of singleton
    static GameManager* sharedGameManager();    

    //A function that returns zero "0" 
    int ReturnZero(){return 0;}
    // another test function
    void runScene() { CCLOG("test");};


and here is my .cpp file:

#include "SimpleAudioEngine.h"
#include "GameManager.h" 
using namespace cocos2d;
using namespace CocosDenshion;

//All static variables need to be defined in the .cpp file
//I've added this following line to fix the problem
GameManager* GameManager::m_mySingleton = NULL;



GameManager* GameManager::sharedGameManager()
    //If the singleton has no instance yet, create one
    if(NULL == m_mySingleton)
        //Create an instance to the singleton
        m_mySingleton = new GameManager();

    //Return the singleton object
    return m_mySingleton;

Here is the call in HelloWorld.cpp:

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) {
    CCLOG("return zero:%d",GameManager::sharedGameManager()->ReturnZero());  // Line 231
    GameManager::sharedGameManager()->runScene();  // Line 232

Here is the weird problem, It’s worked fine with xcode, can build on iPhone. but when i try to build with ndk:

./obj/local/armeabi/objs-debug/game_logic/HelloWorldScene.o: In function `HelloWorld::ccTouchesEnded(cocos2d::CCSet*, cocos2d::CCEvent*)':
/Users/abc/Documents/def/def/android/jni/../../Classes/HelloWorldScene.cpp:232: undefined reference to `GameManager::sharedGameManager()'
collect2: ld returned 1 exit status
make: *** [obj/local/armeabi/] Error 1

If undefined reference to `GameManager::sharedGameManager()’, why the hell the first call is working?

Any help will do, thanks!


Hi, I’m actually porting my code to cocos2d-x and in all honesty finding the Obj C to C++ a pain in the proverbial, in places…

I use a Singleton class (GameManager) in all of my projects in cocos2d and really like the model. Although, I’m not fully there with my implementation, I’m wondering if you had issues converting the following, or if it’s even needed?

Obj C (cocos2d)
+(GameManager*)sharedGameManager { /* Easy to part to translate /
@syncronized([GameManager class]) /
scratches head! */
if(!_sharedGameManager) [[self alloc] init];
return _sharedGameManager;
return nil;

//Are the next two blocks needed in cocos2d-x (i.e. do we need to Alloc/init?
+(id)alloc { /*

-(id)init {
self = [super init];
if (self != nil) {

Like I said, I’m still not there when fully implementing the GameManager to Cocos2d-x (working on other bits…), but I’m almost at the point where I want to move control to a GameManager