Globals in Visual C++
I have created a CLog class for logging during program execution and, next to the declaration of
CxApp theApp;
because that way I can be pretty sure none of the other files will have started running yet, I have declared
CLog g_TheLog;
This comes up in the list of global variables, so I ought to be able to access it from anywhere, right? And, indeed, I can access it from xApp.cpp. But every time I try and access it from elsewhere, eg. with
g_TheLog.AddToLog("Some message");
I am informed that g_TheLog is an undeclared identifier, and the left of .AddToLog() must point to a class, struct or union. In other words, it doesn''t recognise the global variable. But it WILL fill in the AddToLog() or whatever when I type
g_TheLog.
so Visual Studio knows what I mean even if the compiler doesn''t!
Anyone have any clue what is going on here?
This basic question is answered far too often. I''m lazy, so here''s an example:
/* A.h (without inclusion guards, you can do those)
*/
extern int Fish;
[/source]
Now you can use Fish in Something.c.
/* A.c*/int Fish = 12345;
/* A.h (without inclusion guards, you can do those)
*/
extern int Fish;
[/source]
/* Something.c*/#include "A.h"
Now you can use Fish in Something.c.
Thanks everyone. As it happens, this question has been answered in another recent thread, but with a weird title so I didn''t read it until after posting this, so I guess you''re right, NullAndVoid! Sorry for taking up your time, thankyou both!
Study this code:
----------------------------------
// File: clog.h
class Clog {
...
};
extern CLog g_TheLog;
----------------------------------
// File: CLog.c
#include "clog.h"
CLog g_TheLog;
--------------------------------
// Any other C++ source file that uses g_TheLog
#include "clog.h"
void
aFunction (){
g_TheLog.AddToLog("in aFunction().\n");
}
----------------------------------
// File: clog.h
class Clog {
...
};
extern CLog g_TheLog;
----------------------------------
// File: CLog.c
#include "clog.h"
CLog g_TheLog;
--------------------------------
// Any other C++ source file that uses g_TheLog
#include "clog.h"
void
aFunction (){
g_TheLog.AddToLog("in aFunction().\n");
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement