Log in

View Full Version : Global Variables, anyone?


Darkman_X000
05-02-2004, 16:38
So, uh.... how do you use global varibles in C? I am a C++ vet, and this primative programming language and rigid syntax requirements are VERY frustrating!!! :mad:

Thanx for any help you offer

Astronouth7303
05-02-2004, 16:46
I believe that it's either including a header, or using the extern keyword.

I'm the other end of the spectrum: I'm a VB pro, not used to the power and details of C. There's a thread on extern (and probably globals, too).

Adam Shapiro
05-02-2004, 17:44
The easiest way (in my opinion) is to use the extern keyword. You can do this using two methods:

Declare the variable in one file and declare it in each additional file in which it must be used with the extern keyword.
Declare the variable in a file and declare it using the extern keyword in a header file to be included in all files requiring the variable.

I always find that it is easiest to use method two as follows:
main.c (or another file)
#include "globals.h"
int iGlobalVar;
iGlobalVar=1;

globals.h
extern int iGlobalVar;

usingglobals.c
#include "globals.h"
if(iGlobalVar==1)printf("Awesome! It worked! ;)");

Hope this helps.

deltacoder1020
05-02-2004, 22:11
technically, any variable declared at the beginning of a file and not within a function is global variable, but only in file-level scope. To make it span across multiple files, declare it in the other files as well but add "extern" before the other definition (remember, exactly ONE definition of the variable should not have an "extern" in front of it)