Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   Global variable question (http://www.chiefdelphi.com/forums/showthread.php?t=62616)

Nathan 27-01-2008 15:03

Global variable question
 
If I create a global variable in one .c file, can I access this variable from another .c file?

I thought so, but I get the error "symbol 'varname' has not been defined."

Thanks,
Nathan

ay2b 27-01-2008 15:09

Re: Global variable question
 
In one file, define it like this:
Code:

int foo;
And in the other file, define it like this:
Code:

extern int foo;
In the first file, it will define the variable, and allocate the memory space for it. In the second file, it will define the variable, but know that the memory space for it is external to that module.

Nathan 27-01-2008 15:56

Re: Global variable question
 
Great, thanks!

Nathan

jacobhurwitz 27-01-2008 18:02

Re: Global variable question
 
A simple way to make sure this works in all files is to add this to a header (.h) file:

Code:

#ifdef DEFINE_VARS
extern int foo;
#endif

#ifndef DEFINE_VARS
#define DEFINE_VARS
int foo;
#endif

So, what does this do? You have some macro, DEFINE_VARS. If it has already been defined, you declare extern int foo. If it hasn't been defined, you define it and declare int foo. This way, foo is external for all files but one.

I hope this helps.


All times are GMT -5. The time now is 23:49.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi