Global variables

This is a discussion on Global variables within the C Programming forums, part of the General Programming Boards category; Hello people.
How dangerous it is to use global/external variables?
Suppose I have several ".c" and ".h" files in a ...

"Best" solution depends on the problem (that sounds like a cop-out, but it's true).

The problem with global variables is that any old function can modify them. Of course, if you're especially careful that's not going to be an issue, but often you need to make some sort of change that will inadvertently cause you problems.

A safer approach is to create a .c file that has your struct in it, global and static. Then that .c file exports an interface that's used to access the struct. That way you have complete control over your variables; you can't accidentally set one of your pointers to in invalid value; or, at least, there's only one place you can do it instead of ten, or fifty!

For a smaller program, if you trust yourself, you can probably get away with simple global variables. It's easier than defining a new interface and really, there's nothing fundamentally wrong with globals. If you wind up having something that's used in a lot of places, I might recommend encapsulating it for safety and simplicity's sake. For example, you might decide to change your pointers to arrays (for whatever reason). With a proper interface, you don't have to worry about changing all your strdup() calls to strcpy(), etc. Just change it once in the interface's implementation and it magically still works.

So, it can be dangerous, but it's not an inherently bad thing to use globals.