3

我正在尝试编写一个用于维护游戏数据的单例类,它称为GameManager,就像出品的《学习cocos2d》一书一样。

这是我的 .h 文件:

#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");};

};

这是我的 .cpp 文件:

#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;
}

这是 HelloWorld.cpp 中的调用:

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

这是一个奇怪的问题,它在 xcode 上运行良好,可以在 iPhone 上构建。但是当我尝试使用 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

如果未定义对 `GameManager::sharedGameManager()' 的引用,为什么第一次调用有效?

任何帮助都可以,谢谢!

4

1 回答 1

3

您确定您已将您的 cpp 文件与 GameManager 实现(您称之为“这是我的 .cpp 文件”)包含到您的 Android.mk 文件中吗?

于 2012-02-24T16:50:28.253 回答