Search code examples
androidc++android-ndksingletoncocos2d-x

Singleton in cocos2d-x Android


I'm trying to write a singleton class for maintain game data, It's called GameManager, just like the book "Learning cocos2d" produced.

here is my .h file:

#ifndef GameManager_h
#define GameManager_h

#include "cocos2d.h"

class GameManager
{
private:
    //Constructor
    GameManager();

    //Instance of the singleton
    static GameManager* m_mySingleton;

public:    
    //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()
{    

}

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/libgame_logic.so] Error 1

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

Any help will do, thanks!


Solution

  • Are you sure you have included your cpp file with GameManager implementation (to which you refer as 'here is my .cpp file') into your Android.mk file?