473,549 Members | 2,331 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 2622
Kleenex <kl*****@no.nos pam> wrote in
news:RNj4d.1064 46$yh.72915@fed 1read05:
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.nos pam> 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$y h.72915@fed1rea d05> Kleenex <kl*****@no.nos pam> 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*********@ea rINVALIDthlink. 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_Keit h) 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.or g> Keith Thompson <ks***@mib.or g> 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.or g> 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*********@ea rINVALIDthlink. 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_ELEMENT S ];

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

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

Similar topics

14
3287
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 $name;
13
1631
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): return a + b
6
2017
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 code: #def put_file(file_id, delete=False): # """ Function to put the file on the FTP Server # """ # print " FTP for this file...
3
5714
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
1915
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 that says 'never' do this, or that. 1. I have 3 site folders s1, s2, s2 and a common DB folder outside the site roots. /sites/s1 /sites/s2
16
2264
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 window open, if I click the link from the email again I get the desired page. The results are the same if the url is copied and pasted into the brower...
9
8627
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 Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the...
2
1108
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 call it MyGlobals and load all my global vars into it at the start and then access this, any of my class files throughout my app can get to the...
0
1432
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* program wide globals. There are only module wide globals. Also, the "global isglobal" is absolutely meaningless as anything declared there is a...
0
7546
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7471
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7740
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7985
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7503
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6071
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5111
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1962
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 we have to send another system

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.