tags:

views:

217

answers:

2

Possible Duplicate:
Undefined reference - C++ linker error

Now, I'm getting an "Undefined reference error message to 'GlobalClass::s_instance', and 'GlobalClass::instance()', respectively on these statements:

GlobalClass *GlobalClass::s_instance = 0;

GlobalClass::instance()->set_value(myAddress);  \\ <== undefined reference    
std::cout << "====>address is is " << GlobalClass::instance()->get_value()

Any ideas? The code is shown below:

================================================

#ifndef GLOBALCLASS_H_
#define GLOBALCLASS_H_

#include <string>
class GlobalClass {

public:

    std::string get_value();

    void set_value(std::string);

    static GlobalClass *instance();

    static GlobalClass *s_instance;

private:

    std::string m_value;
};

#endif /* GLOBALCLASS_H_ */

===============================================

#include <string>
#include "GlobalClass.h"



/*
 GlobalClass(int v = 0)
 {
 m_value = v;
 }
 */

    static GlobalClass *s_instance;

    std::string GlobalClass::get_value()
    {
        return m_value;
    }

    void GlobalClass::set_value(std::string v)
    {
        m_value = v;
    }

    static GlobalClass *instance() {
        if (!s_instance)
                s_instance = new GlobalClass;
        return s_instance;
    }

===========================================================

#include <iostream>
#include "GlobalClass.h"

using namespace std;

int main() {

    GlobalClass::s_instance = 0; \\ <== undefined reference 


    std::string myAddress = "abc";
    GlobalClass::instance()->set_value(myAddress);  \\ <== undefined reference

    std::cout << "====>address is is " << GlobalClass::instance()->get_value() 
    \\ <== undefined reference

                 << std::endl;
    return 0;

}

+2  A: 

In your CPP file, move "Global::s_instance = 0;" outside of main(), and prefix it with static, e.g.

static Global::s_instance = 0;
int main()
{
...
}
Alex Black
+2  A: 

Further to Alex Black's response, its complaining that the GlobalClass::instance() function does not have an implementation. Which it doesn't:

static GlobalClass *instance() {
        if (!s_instance)
                s_instance = new GlobalClass;
        return s_instance;
    }

That really ought to be:

GlobalClass *GlobalClass::instance() {
            if (!s_instance)
                    s_instance = new GlobalClass;
            return s_instance;
        }

Don't forget that even though it is static it is still a member function!

Goz
That was probably it. Sheesh!
Jack BeNimble