Skip to main content
gamedev.net
🔒 Locked

Global Objects & Extern

Started by imDivineLight Jun 27, 2004 at 9:12 PM 3 replies 850+ views
Original Post
imDivineLight
imDivineLight
i am having a hard time with my global logger, in my engine, i have a file named globals.h in it i have this static Logger gLog("Log.html"); and now if i want to use it what i have to do? i have done extern Logger gLog; in top of every header which uses this global object but no sucess. can you please provide a little example of global object with extern & do i have to use extern or some other method?
::- Hear the beauty of silence -::
ApochPiQ
ApochPiQ
If you #include globals.h in more than one file, it is a bad idea to define variables there. You're also misusing the "static" keyword. When you have a "static" variable that is not in a class or function, it tells the compiler that no other file should be able to use the variable. (See MSDN for more details.) A better way to do it would be to have something like this:

// In globals.hextern Logger gLog;// In somefile.cpp#include "globals.h"void SomeFunction(){ gLog.DoSomething();}


Better yet, have a look at singletons.
hplus0603
hplus0603
If you make something static, it means that it's only available in that translation unit.

If you make it static in a header, it means that each translation unit including that header gets its own copy.

ApochPiQ is mostly right -- you also need to have, in a single source file, the definition of the logger.

// in globals.h:#include <Logger.h>// in Logger.h:class Logger { ... };extern Logger gLog;// in most files.cpp:#include "globals.h"gLog.Log( "hello, world!\n" );// in Logger.cpp:Logger gLog( "Log.html" );


Note that you have to include the declaration of the class Logger to actually be able to use it in the other files.
enum Bool { True, False, FileNotFound };
ApochPiQ
ApochPiQ
Good catch. I guess I'm so used to doing that in my own code that I just take it for granted [wink]
imDivineLight
imDivineLight
Thanks buddys this helps me! all is fixed.
You'r Ratings up! :)
::- Hear the beauty of silence -::

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.