Alex Rivera | Logout

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

Asked 2009-05-16T18:09:05.520
39

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.)

Edit
Report

2 Answers

7

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.

answered 2009-05-18T09:34:35.953
3

It is a matter of scope. We have developers that love to make global variables to do local concepts. It make the usage of these variables much harder to keep track of, so it is easier to make mistakes in the use of them.

You can keep your wallet on your front porch also, but then you have far less control over who is accessing it.

That being said there are some valid uses for Global variable, but like any other rule worth following. This is the exception not the normal case. Their very existing points out that they have a use.

If you do decide to use a global variable try to comment them well and give them good names. It really bothers me when people make global variables like "bool bIsFound;"

We make it a point to evaluate each new global variable in code review and see if there is a better approach.

answered 2009-05-16T18:27:08.410

Your Answer