Sign in to follow this  
flammable

[c++] problem with a global instance of a class

Recommended Posts

Hey I've a problem, I'll first explain what I try to do. Create a class and a global instance of that class that can be accessed from everywhere I include the right header file, like how std::cout works (as far as I understand). I figured that the extern keyword was needed in this case and what I've done is this:
class Test_
{
	public:
		void greet()
		{
			std::cout << "Hello World!";
		}

};

extern Test_ Test;

and that gives the following linker error (I'm using visual studio c++ 2008):
1>main.obj : error LNK2001: unresolved external symbol "class Test_ Test" (?Test@@3VTest_@@A)
1>C:\Documents and Settings\gebruiker\Bureaublad\test\Debug\test.exe : fatal error LNK1120: 1 unresolved externals

I noticed that everything linked fine when I changed the last line into this:
extern Test_ Test = Test_();

but in the real case this isn't practical, and std::cout seems to do without it (but I'm sure I'm missing something). I hope someone can help, thanks in advance.

Share this post


Link to post
Share on other sites
extern means: is actually instanced elsewhere. They typical extern pattern is

MyClass.h file

extern MyClass gAnInstance;




MyClass.cpp file

MyClass gAnInstance; //this is the actual instance




Remember always that the problem with global instances declared like that is unreliable destructor calling. Order of operations won't be guaranteed. If you really need a global it's often better to have the global be declared as a pointer initialized to NULL. During your main program init method block instance that pointer and in your main application shutdown method delete the instance:

Only at the top of files that need it:

extern MyClass *gAnInstance;



probably in your main.cpp file:

MyClass *gAnInstance = NULL; //this is the actual instance




void init()
{
gAnInstance = new MyClass();
}

void shutdown()
{
delete gAnInstance;
}

void main
{
init();

//your game loop
while (1)
{
}

shutdown();
}



There are a lot of other things that go into globals like designing the class so it's a singleton or whatever. but I won't bother with that here. just google "singleton"

-me

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this