#### Archived

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

# Using Globals from one header file in another

This topic is 5379 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello All Id like to know which is the best possible way to use global variables in one header file in other header files. e.g main.h has: HDC g_hDC; HWND g_hWnd; and another header (main2.h) includes this header (main.h). Problem is that when I link them it says it''s already defined in main.obj which I get. But what''s the best way to solve this? Most of the time I use static on them, is there another, better way? Thanks

##### Share on other sites
A simple solution is to use "extern" on the declarations in the header file, and then define them for real (without "extern" or "static" in a single C file. As an aside, you might want to reconsider a design that calls for a bunch of global variables.

##### Share on other sites
main.h

HWND g_hWnd

---------------

window_init.h

extern HWND g_hWnd;

##### Share on other sites
Like one of the other posters mentioned, you might want to reconsider an approach that uses a lot of globals. That said, here''s something I''ve found that helps if you''re in an environment that uses a lot of globals.

In your example, in the main.h, I would put...

#ifndef SETGLOBALextern HDC g_hDC;extern HWND g_hWnd;#elseHDC g_hDC;HWND g_hWnd;#endif

#define SETGLOBAL#include "main.h"#under SETGLOBAL

Then, in your main2.h, just have...

#include "main.h"

What this does, is it uses precompiler definitions to only set your globals once. The idea is, you only want to have ''HDC g_hDC'' once, and all the other files should have ''extern HDC g_hDC''. So, to do this, you just set up the default behavior to be ''extern HDC g_hDC''. But, in one cpp file (no more, no less), you put a ''#define SETGLOBAL'' before you include the main.h, so that file doesn''t have the extern.

##### Share on other sites
silly people ... do not define variables in header files, that''s your first problem .. you should only declare them.

In any header file, when you have a variable you wish to declare, use the "extern" keyword ... so:

//main.h

#include <windows.h>

extern HDC g_hDC;
extern HWND g_hWnd;

// main2.h

#include <windows.h>

#include "main.h"

// ...

and then in main.c or main.cpp or whatever you DEFINE the variables:

// main.cpp

HDC h_hDC;
HWND g_hWnd;

and that''s all there is to it. Never allocate storage in a header file, cause then it isn''t a header file (by my definition) ... C++ doesn''t even have a concept of header files, but my definition is this - any file which may be included multiple time in a project is a header file (so only templates, macro definitions, and declarations can go in them), and any file which can only be inlcuded once is not a header file.

This rule keeps things simply ...

##### Share on other sites
Thanks You Guys :D