Archived

This topic is now archived and is closed to further replies.

DirectAndy8

Globals in Visual C++

Recommended Posts

DirectAndy8    122
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?

Share this post


Link to post
Share on other sites
Null and Void    1088
This basic question is answered far too often. I''m lazy, so here''s an example:
  
/* 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.

Share this post


Link to post
Share on other sites
DirectAndy8    122
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!

Share this post


Link to post
Share on other sites
poozer    122
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");
}


Share this post


Link to post
Share on other sites