??? 10/31/05 01:32 Read: times |
#103156 - globals are generally bad ... Responding to: ???'s previous message |
Now that the others have answered your question, I'm going to stir the pot a little bit and ask, "why are you using globals?"
Admittedly, for small designs, globals may not be evil, and perhaps even the constraints of embedded systems (limited memory, etc) make them attractive. But once you get into programs with more than one source file, it becomes difficult to keep track of what goes where. "Where was this variable declared? Where is it being used?" If you're forward-thinking enough to break up your programs into multiple source files, then perhaps you should consider using parameters in the calls to the functions in those source files. You can use the fact that globals declared in a source file have only file scope (in other words, not visible to other sources in the design) to your advantage. You can think of the functions in the source file as being methods in a "class," and then these "local globals" can be considered private data members. They're "private" because only functions in the source file can access them. A quick example: say you have some functions in a source file that handle writing to an LCD. You may have one function called WriteStringAt(str, lineloc, charpos) which writes the string str to line lineloc at position charpos. You may also have a function called WriteString(str), which would simple write str to the display starting at the next location. You could implement the location (line, character position) as a couple of globals to be externed and such, or as I advocate, you could simply declare them as globals in your lcdfuncs.c (and not in the header, lcdfuncs.h). This way, you don't have to keep track of these globals in the rest of your program (since you don't care). OK, so maybe you DO need to know the current character position, so then you write a little function to return them. Sure, a few more bytes, but you gain modularity and you don't have to worry that other functions elsewhere in the program may step on your variable called x. OK, I can think of one area where globals are necessary: interrupt-service routines. These routines cannot accept function parameters, nor can they return values. Thus, any variables modified by the ISR must be globals. Of course, your ISR should do little more than set a flag and return, so there shouldn't be a need for many globals. -a |
Topic | Author | Date |
Using Multiple C files in SDCC | 01/01/70 00:00 | |
Not about the compiler | 01/01/70 00:00 | |
Nothing to do with SDCC | 01/01/70 00:00 | |
The joy of C | 01/01/70 00:00 | |
Sloppy terminology | 01/01/70 00:00 | |
Using Multiple C files in SDCC | 01/01/70 00:00 | |
Laziness | 01/01/70 00:00 | |
example | 01/01/70 00:00 | |
globals are generally bad ... | 01/01/70 00:00 | |
"Generally" being the important word! | 01/01/70 00:00 | |
re Globals![]() | 01/01/70 00:00 | |
static | 01/01/70 00:00 |