What is the best strategy for sharing variables between source files in c/c++?

baconeer picture baconeer · Aug 1, 2013 · Viewed 10.8k times · Source

I frequently have to write c/c++ programs with 10+ source files where a handful of variables need to be shared between functions in all the files. I have read before that it is generally good practice to avoid using global variables with extern. However, if it is completely necessary to use global variables, this link provides a good strategy. Lately, I have been toying with the strategy of wrapping up all my variables in a struct or a class and passing this struct around to different functions. I was wondering which way people consider to be cleaner and if there are any better alternatives.

EDIT: I realize strategies may be different in the two languages. I am interested in strategies that apply to only one language or both.

Answer

Neil Kirk picture Neil Kirk · Aug 1, 2013

Pass around a class/struct of "context" data instead of global variables. You will be suprised how often a global variable becomes no longer global, with different modules wanting to use different values for it at the same time.