Advertisement

share variables across files

Started by April 12, 2001 06:35 AM
3 comments, last by dadio 23 years, 7 months ago
Hi All, I know this is a simple one.....but: I do I share global variables in a VC++ project on more than one file? thx.
For every .c or .cpp file you make, have a header file that looks somewhat like this:

THE HEADER FILE
  #pragma once#ifndef INC_SOME_HEADER#define INC_SOME_HEADER/* ... */extern int MyGlobalInt;extern int MyGlobalInt2;extern void MyFunction(void);#endif  

THE C/C++ FILE
  /* ... */int MyGlobalInt;int MyGlobalInt2 = 382;void MyFunction(void) {  /* ... */}  

Now, include that header file in every other file that you wish to have access to that file''s functions and variables.

"Finger to spiritual emptiness underlying everything." -- How a C manual referred to a "pointer to void." --Things People Said
Resist Windows XP''s Invasive Production Activation Technology!
http://druidgames.cjb.net/
Advertisement
use a header file

ex:
in a file named myHeader.h:
int myGlobal;

and in every file you want to use myGlobal:

#include "myHeader.h"


lunasol
quote: Original post by lunasol

use a header file

ex:
in a file named myHeader.h:
int myGlobal;

and in every file you want to use myGlobal:

#include "myHeader.h"

You know that that will create a new myGlobal for each file that it is included in? You''re meant to put it in a single code file and use extern so that other files know that it exists in other files, and that file doesn''t need its own copy of that variable.


"Finger to spiritual emptiness underlying everything." -- How a C manual referred to a "pointer to void." --Things People Said
Resist Windows XP''s Invasive Production Activation Technology!
http://druidgames.cjb.net/
you''re damn right Null and Void!!

extern lunasol

This topic is closed to new replies.

Advertisement