473,499 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Managing global vars between files

Reason: I am working on an embedded project which has very limited
memory (under 512 bytes, 60 or so of which is stack space), which
translates into limited stack space. In order to save on stack space, I
tried to only use parameters and stack space for things which are truely
temporary. Instead of passing a pointer to a data structure which should
always be populated with data, I have the data structure declared as a
global variable and all functions access it directly. This works fine
until I try and organize the code into seperate files.

Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across files,
but this leads to every file, except the main source file, having a nice
long list of exported vars at the beginning. Is there a better way to
make global vars in C, outside of declaring in 1 file, and exporting in
every other file that uses the variable?
Nov 14 '05 #1
10 2612
Kleenex <kl*****@no.nospam> wrote in
news:RNj4d.106446$yh.72915@fed1read05:
Reason: I am working on an embedded project which has very limited
memory (under 512 bytes, 60 or so of which is stack space), which
translates into limited stack space. In order to save on stack space, I
tried to only use parameters and stack space for things which are truely
temporary. Instead of passing a pointer to a data structure which should
always be populated with data, I have the data structure declared as a
global variable and all functions access it directly. This works fine
until I try and organize the code into seperate files.
I've used smaller parts (128B) without globals but that's not the point
here, I admit.
Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across files,
but this leads to every file, except the main source file, having a nice
long list of exported vars at the beginning. Is there a better way to
make global vars in C, outside of declaring in 1 file, and exporting in
every other file that uses the variable?


If you have a "database" of global'ish data then put them all in a struct.
Then put the struct declaration and an extern of the struct object in a
file, like db.h, and include it from all files that require the
"database".

--
- Mark ->
--
Nov 14 '05 #2
Kleenex <kl*****@no.nospam> writes:
Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across files,
but this leads to every file, except the main source file, having a
nice long list of exported vars at the beginning. Is there a better
way to make global vars in C, outside of declaring in 1 file, and
exporting in every other file that uses the variable?


C doesn't have anything called "export". It has "extern",
though.

The usual way to use global variables is to declare them once,
with "extern", in a header file, e.g.

foo.h:

extern int foo;
extern double bar[];
extern void (*x) (double, int, ...);

Then each file that uses the globals includes the header:

#include "foo.h"

Exactly one .c file should actually define the global variables,
optionally with initializers:

int foo = 20;
double bar[] = {1, 2, 3, 42, 67, 128};
void (*x) (double, int, ...);
--
"Welcome to the wonderful world of undefined behavior, where the demons
are nasal and the DeathStation users are nervous." --Daniel Fox
Nov 14 '05 #3
In <RNj4d.106446$yh.72915@fed1read05> Kleenex <kl*****@no.nospam> writes:
Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across files,
but this leads to every file, except the main source file, having a nice
long list of exported vars at the beginning. Is there a better way to
make global vars in C, outside of declaring in 1 file, and exporting in
every other file that uses the variable?


You have just discovered one of the main reasons for using header files.
Put all the extern *declarations* in a header file that is included by
all the other source files. Put the corresponding *definitions* only in
one source file (not all of them need to be in the same source file, but
none of them should be in more than one source file).

This way, adding or removing one global only requires changes in two
files, which is a lot more manageable than changing all the source files
of the application.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #4
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.

--

Paul Hirose <ew*********@earINVALIDthlink.net>
To reply by email delete INVALID from address.

Nov 14 '05 #5
Kleenex wrote:
Reason: I am working on an embedded project which has very limited
memory (under 512 bytes, 60 or so of which is stack space), which
translates into limited stack space. In order to save on stack space, I
tried to only use parameters and stack space for things which are truely
temporary. Instead of passing a pointer to a data structure which should
always be populated with data, I have the data structure declared as a
global variable and all functions access it directly. This works fine
until I try and organize the code into seperate files.

Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across files,
but this leads to every file, except the main source file, having a nice
long list of exported vars at the beginning. Is there a better way to
make global vars in C, outside of declaring in 1 file, and exporting in
every other file that uses the variable?


You're nuts.

You won't save any space by using global variables
and you will make your code virtually impossible to maintain.
You need to re-think your designs and eliminate global variables.
Nov 14 '05 #6
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Kleenex wrote:
Reason: I am working on an embedded project which has very limited
memory (under 512 bytes, 60 or so of which is stack space), which
translates into limited stack space. In order to save on stack
space, I tried to only use parameters and stack space for things
which are truely temporary. Instead of passing a pointer to a data
structure which should always be populated with data, I have the
data structure declared as a global variable and all functions
access it directly. This works fine until I try and organize the
code into seperate files.
Problem: I know I can declare a global var in 1 file, and declare it
with export in another so I can use that same global var across
files, but this leads to every file, except the main source file,
having a nice long list of exported vars at the beginning. Is there
a better way to make global vars in C, outside of declaring in 1
file, and exporting in every other file that uses the variable?


You're nuts.

You won't save any space by using global variables
and you will make your code virtually impossible to maintain.
You need to re-think your designs and eliminate global variables.


Really? Local variables are likely to be allocated on the stack, of
which the system only has 60 bytes; global variables are likely to be
allocated in non-stack memory, of which there's about 450 bytes. It
seems plausible that using global rather than local variables makes
sense in these unusual circumstances.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #7
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
You're nuts.

You won't save any space by using global variables
and you will make your code virtually impossible to maintain.
You need to re-think your designs and eliminate global variables.


Really? Local variables are likely to be allocated on the stack, of
which the system only has 60 bytes; global variables are likely to be
allocated in non-stack memory, of which there's about 450 bytes. It
seems plausible that using global rather than local variables makes
sense in these unusual circumstances.


Furthermore, if used properly, global variables don't have a negative
impact on the code readability/maintenability.

For the small bits of local data needed by most functions (loop counters,
temporary variables and so on) static allocation can be used instead of
automatic allocation. Embedded control applications running on platforms
with this kind of resources seldom use recursive functions...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #8

"Keith Thompson" <ks***@mib.org> wrote

Really? Local variables are likely to be allocated on the stack, of
which the system only has 60 bytes; global variables are likely to be
allocated in non-stack memory, of which there's about 450 bytes. It
seems plausible that using global rather than local variables makes
sense in these unusual circumstances.

Exactly. The normal rule is that globals are a Bad Thing, but there are
always exceptions.
What you probably want to do is to declare a few variables g_temp1, g_temp2
etc, with the understanding that their value may be corrupted by a
subroutine. Leaf routines can use these variables at will, non-leaf if they
do so carefully. That way your precious memory space is reused.
Nov 14 '05 #9
Paul Hirose <ew*********@earINVALIDthlink.net> writes:
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 */

[...Then different #include's will get either declarations or ]
[ definitions depending on whether MAKE_DEFS is defined ]

Clearly there are benefits to having declarations and definitions
automatically synchronized, as is accomplished by this approach.

Using the C preprocessor to effect this synchronization has some
difficulties. It doesn't read very nicely for initializing arrays
or struct's, for example. Also, a common pattern is to declare
an array

extern SomeType some_array[];

whereas the definition might read

SomeType some_array[ MAXIMUM_ELEMENTS ];

which isn't accommodated by using GLOBAL and EQUALS.

A different approach, fairly simple to implement, is to find and
textually process global variable definitions, producing a header
file with declarations that may be #include'd. For example,

int a, b = 2;

unsigned long masks[5] = {
0x55555555,
0x33333333,
0x0f0f0f0f,
0x00ff00ff,
0x0000ffff,
};

would produce the declarations

extern int a, b;

extern unsigned long masks[];

in the resulting declaration header. I wrote such a tool for a
lightweight development environment and now use it routinely in any C
development work. It's surprisingly liberating.

Anticipating the next question - yes, the DE also automatically
generates and incorporates function prototypes along with variable
declarations. That has turned out to be amazingly beneficial. My
normal development mode now is compiler flag settings that require
prototypes for ALL functions, and duplicate prototypes not allowed.
No extra work to make that happen - just edit source files as usual,
and all the necessary generation gets done automatically. It's hard
to imagine going back now to doing that stuff by hand.
Nov 14 '05 #10
I wanted to thank everyone for their replies, even Tisdale (who I hope
has a fake email address). I have implemented my own version of the
header suggestions, and it appears to be working well.

Thanks again.
Nov 14 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3281
by: lkrubner | last post by:
If I set a variable at the top of my code like this: $name = "Lawrence"; It is now a global variable. If, later on, in a function, I want to do this: function uppercaseName() { global...
13
1620
by: David Rysdam | last post by:
Getting no answer yesterday, I've done some investigation and I obviously don't understand how python namespaces work. Here's a test program: #!/usr/bin/python b = 2 def sumWithGlobal(a):...
6
2013
by: flamesrock | last post by:
ok, so to my knowledge, object oriented means splitting something into the simplest number of parts and going from there. But the question is- when is it enough? For example I have the following...
3
5707
by: | last post by:
my global.asa file doesn't seem to be executing in IIS and i don't know how to make them run. Any ideas how to execute the global.asa file in IIS 5.1 , please let me know. thank you very much.
4
1910
by: Kenny Ashton | last post by:
Hello gurus Can I ask you opions on the best compromise for storing Access Ado connection strings in a IIS4 standard ASP environment. For any method I use, there seems to be an article somewhere...
16
2256
by: WaterBug | last post by:
When clicking on the following link from an email i.e - http://myserver/myapplication/myprogram.asp?urlvar1=some%20stuff&urlvar2=more%20stuff I get a server 500 error. With that same browser...
9
8609
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang...
2
1102
by: PokerMan | last post by:
Hey guys Can people give me their views on this. When i make a cs class file for my asp.net app i cant use Application objects for my globals? But if i was to make a singleton class say and...
0
1428
by: Gary Herron | last post by:
Jacob Davis wrote: Yuck, YUCK, YUCK! You are breaking *so* many good-programming-practices, I hardly know where to start. First off: A python global is not what you think. There are *no*...
0
7006
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7215
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6892
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7385
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5467
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4917
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4597
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1425
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.