Why are global variables bad, in a single threaded, non-os, embedded application

20,083

Solution 1

It wouldn't.

The two fundamental issues with global variables is simply cluttering the namespace, and the fact that "no one" has "control" over them (thus the potential collisions and conflict with multiple threads).

The "globals are bad", like pretty much every other computer programming idiom is a guideline, not a hard and fast rule. When these kinds of "rules" are made, its best rather than simply adopting the rule by rote to understand the circumstances and motivations behind the creation of the rule. Don't just take them blindly.

In your case, you seem to understand the nature of your system and the arguments around the rule and decided that it doesn't apply in this case. You're right, it doesn't.

So, don't worry about it.

Solution 2

Global variables are not necessarily bad, just as macros are not necessarily bad, and enriched uranium is not necessarily bad. As long as you make a conscious decision about the pros and cons of a given design choice, you should be all right.

Some of the arguments against global variables are:

  1. They violate good object-oriented design
  2. They make your code difficult to unit-test, since you can not test individual blocks of code without setting up all of the global variables that the code expects to see
  3. They increase coupling in your code: actions in one block of code may affect things in another block of code in unpredictable ways via a shared global variable

Some of the arguents for global variables:

  1. They make it easy to share a single resource between many functions
  2. They can make code easier to read

If, in your design, global variables make sense, and can be used to make your code simpler to read or easier to maintain, without setting yourself up for random errors and testing headaches, then by all means use them.

I write a lot of C code for embedded microcontrollers, and I use global variables all the time. In such a rigid system, global variables make sense. I'm aware of the potential drawbacks, but I have analyzed the pros & cons and I write my code so as to guard against the major pitfalls.

Bottom line: There is no hard and fast rule. Just make the best decision for your particular project or platform, based on the best information that you have.

Solution 3

Here is a good article that gives reason Why global variables are Bad

Why Global Variables Should Be Avoided When Unnecessary?

Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use. No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten.

Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.

Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.

Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort that aren't explicitly provided to that source is difficult to test for the same reason.

Adding globals is really easy. It's easy to get in the habit of declaring them. It is much faster than thinking of a good design.

Global variables are not as bad as you may think, they just should be avoided whenever unnecessary. Global variables can have good use for a variable that would be used thoughout the program,making sure you keep in mind that you always have to keep track of where that variable takes changes; but for variables that tend to be only used within limited parts of the program is good reason to avoid having it global.

Solution 4

Global variables are necessary in a small embedded application written in C. For example, you need to use a global variable in order to pass information between an Interrupt Service Routine and another module. These are some tips, that will help you make effective use of global variables in embedded applications:

  • Make a distinction between static variables and global variables. Static variables can be used from all functions in the same C file. They are the equivalent of private members in a C++ class. In C you have to do the compiler's job yourself. Use the static keyword to avoid accidental use of the variable outside of the module and make evident its scope. You may want to prefix the variable with the module's name.

  • Follow a naming convention for global variables (used by many C files). Make it clearly evident that they are global.

  • If you need a lot of global variables, consider bundling them in a struct.

  • Use the volatile keyword, when necessary. This is needed if a global variable is modified by an ISR.

Solution 5

Because it minimizes coupling. Your system may be small now but if you keep on working, it may turn out not to be.

Share:
20,083
loneRanger
Author by

loneRanger

Updated on December 06, 2020

Comments

  • loneRanger
    loneRanger over 3 years

    Most of the objections I see to using global variables make sense since they refer to issues of multiple threads, thread safety, etc.

    But in a small, single threaded, non-OS, case, what objections do you have? In my case, I'm writing my embedded system in "C", if it matters. I'm also the only developer on the product.

    Why would eliminating global variables make my code better?

    (After reading several responses, I realize I also should have pointed out that this system has no dynamic memory allocation (e.g. malloc). All the memory is statically allocated at compile time.)

  • rampion
    rampion almost 15 years
    This is the point I wanted to make. Just because it's small and single threaded now doesn't mean it will always be.
  • Nathan Fellman
    Nathan Fellman almost 15 years
    Why is that not true with pointers? If I have a variable that's passed by pointer to another function, it isn't always easy to see where its value was changed.
  • Admin
    Admin almost 15 years
    rampion: missing the point, which is decoupling for reusability, not thread safety.
  • Steve Melnikoff
    Steve Melnikoff almost 15 years
    Agreed. Like so many "rules" in software (especially C), there are times when the situation requires that they be bent or broken. I try to avoid globals as much as possible, but there are a small number of occasions when they are the best solution to a problem.
  • Marco van de Voort
    Marco van de Voort almost 15 years
    Global values can be only be seen by modules that include the module that they are defined in. Following that logic one could outlaw public and protected fields because everybody can gain access to them by inheriting.
  • loneRanger
    loneRanger almost 15 years
    I appreciate the many comments and answers. I selected this as my answer because it most clearly summarizes my rationale. I do feel 'funny' choosing an answer that validates my design choices, but hey, I guess I will anyway.
  • smerlin
    smerlin almost 14 years
    global variables can make the code more difficult to read aswell... and IMO thats more likely.
  • Ellis
    Ellis almost 9 years
    This is one of the best answers I have ever read on this site.
  • ForeverLearning
    ForeverLearning over 5 years
    Great complement to the main answer!