how to handle global variable?

Started by
1 comment, last by microdot 19 years ago
if I have a class D3D; and a variable D3D myD3D; this variable will be used all of program. how to handle this variable? like extern D3D myD3D,I don't like this sentence appear every file on my project. this will add complex .
Advertisement
Your good friends K&R added a wonderful feature to C to solve your problem. Look into the #include directive. "But", you say, "I'm using C++, not C". In his wisdom, Stoustrup decided that #include was a good thing and allowed it in C++ as well.
Expounding upon what the AP said, to have a global variable that you can share across translation units, you want to put the following into a header file. Say "globals.h"
extern D3D myD3D ;

Then, in the source file ("globals.cpp") you'd put the following.
D3D myD3D ;

Viola! Everywhere you include "globals.h", you will have access to myD3D.

Now, there are many who believe that globals are bad mojo. So alternatively, you might consider looking into makeing your D3D class a Singleton or Monostate. Then again there are those who believe using Singletons as surrogate globals is also bad.

Anywho, hope that helps.
<span class="smallfont">That is not dead which can eternal lieAnd with strange aeons even death may die.   -- "The Nameless City" - H. P. Lovecraft</span>

This topic is closed to new replies.

Advertisement