Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Managing global vars between files
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
Reply to thread
Message
[QUOTE="Paul Hirose, post: 2387767"] I've written some C programs with many global variables shared by several source files. My solution was something like this: /* File globals.h Every file needing access to the global variables #includes this file. Exactly one of those files must #define MAKE_DEFS before the #include. That will trigger generation of definitions. */ /* set up the preprocessor */ #ifdef MAKE_DEFS /* generate definitions */ #define GLOBAL /* expand GLOBAL to nothing */ #define EQUALS(x) =x #else /* generate declarations only */ #define GLOBAL extern #define EQUALS(x) /* expand initializer macro to nothing */ #endif /* then create a couple global variables, one with an initializer */ GLOBAL int a; GLOBAL int b EQUALS(2); /* end of file */ If #define MAKE_DEFS has been seen, the preprocessor converts those two lines to: int a; int b = 2; Otherwise, they become: extern int a; extern int b; To save myself the trouble of remembering where the definitions were generated, I used a file named globals.c for that purpose. It had just 2 lines: #define MAKE_DEFS #include "globals.h" It's been many years since I used that technique (the code is on 5.25" floppies, that's how long ago) and I'm writing this off the top of my head, but that's basically how it was done. The idea isn't mine, by the way. I got it from a book. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Managing global vars between files
Top