I\'m getting an Undefined reference error message, on this statement:
GlobalClass *GlobalClass::s_instance = 0;
Any ideas? Code is shown be
Are you trying to implement a Singleton class? Ie. You want only a single instance of of the class, and you want that instance available to anyone who includes the class. I think its commonly known as a Singleton, the following example works as expected:
Singleton.h:
#include <string>
class Singleton
{
public:
static Singleton* instance()
{
if ( p_theInstance == 0 )
p_theInstance = new Singleton;
return p_theInstance;
}
void setMember( const std::string& some_string )
{
some_member = some_string;
}
const std::string& get_member() const
{
return some_member;
}
private:
Singleton() {}
static Singleton* p_theInstance;
std::string some_member;
};
Singleton.cpp:
Singleton* Singleton::p_theInstance = 0;
main.cpp:
#include <string>
#include <iostream>
#include "Singleton.h"
int main()
{
std::string some_string = "Singleton class";
Singleton::instance()->setMember(some_string);
std::cout << Singleton::instance()->get_member() << "\n";
}
Note that the constructor is private, we don't want anyone to be creating instances of our singleton, unless its via the 'instance()' operator.
When you declare a static field s_instance
in your .h file, it only tells the compiler that this field exists somewhere. This allows your main
function to reference it. However, it doesn't define the field anywhere, i.e., no memory is reserved for it, and no initial value is assigned to it. This is analogous to the difference between a function prototype (usually in a .h file) and function definition (in a .cpp file).
In order to actually define the field, you need to add the following line to your .cpp file at global scope (not inside any function):
GlobalClass* GlobalClass::s_instance = 0;
It is important that you don't add the static
modifier to this definition (although you should still have the static
modifier on the declaration inside the class in the .h file). When a definition outside a class is marked static
, that definition can only be used inside the same .cpp file. The linker will act as if it doesn't exist if it's used in other .cpp files. This meaning of static
is different from static
inside a class and from static
inside a function. I'm not sure why the language designers used the same keyword for three different things, but that's how it is.
If I understand what you want to do is only a matter of using this:
GlobalClass::s_instance = 0;