Re: Global variable
<keralafood@gmail.com> wrote in message
news:1192698448.786104.165730@i38g2000prf.googlegroups.com...
How i can avoid global variable in my program?
I use 10-15 global variable because i have to use it different
callback functions(all are system callback, like hook,directX
etc...)is there any way to avoid this?
i must use these variables(some variable using in different file as
external variable)
any advice really appreciable
thanks
NB: this forum is the best forum in programming ,no doubt about it.
Either put your global variables in your CWinApp-derived class as was
suggested, or else create another class with all-static members, e.g.:
[MyGlobals.h]
class CMyGlobals
{
public:
static int m_nFoo;
static CString m_strBar;
...
};
[MyGlobals.cpp]
// instantiate global vars
int CMyGlobals::m_nFoo;
CString CMyGlobals::m_strBar;
Then whenever you need to access it, simply
#include "MyGlobals.h"
if ( CMyGlobals::m_nFoo == 3 )
whatever;
As you can see, making CMyGlobals have all static variables makes it
extremely easy to reference the global variables without even worrying
getting the instance of the CMyGlobals class. This is truly easy, and the
resulting syntax reads very well also. Compared to the CWinApp approach:
CMyApp *pMyApp = (CMyApp *) AfxGetApp();
if ( pMyApp->m_nFoo == 3 )
whatever;
This code is OK, but it spends as many lines of code getting the pMyApp
instance as it does accessing the m_nFoo member, which in my mind is not a
very concise way to program.
-- David