remove global variables in c++ program

c++, data-structures

Solution

I normally start by putting the global variables in a namespace

namespace global
{
  int var;
  ...
}

this will cause you to get errors everwhere that 'var' is used, then i would just replace the references one by one to the namespace variant. once all global variable references are in the namespace it is easier to see which variables are local and which are global

if ( global::var == 1 ) ...

now by searching `global::var` you get a list of variables where it is used then you would need to go through the usage case by case to see if a variable is used in several modules or not, in those cases you may need to pass it in as a function argument in other cases declare it is a local variable.

its a cumbersome method but eliminating global vars is always worth doing.

Problem

I have a large program in c++ having too many function and global variables. Now, I want to remove those global variables and I want to use only local variables rather than global variables. Can any one suggest me the best way to do this. Thanks! Its around 4000 lines program in C++. There are 10 classes and 60 functions in those different classes, 30 global variables. The global variables have used between functions of different classes.

Original source