if the code is working and done, going back to clean it up may be very hard. The key is to not use them at all when writing new code once you realize they are generally bad practice.
As far as it goes, you can wrap global variables in a large established project into a class, using static class member variables, and they will still be effectively global and behave as before, but now you must explicitly call upon them so you can't accidentally have a local/global/parameter of the same name or otherwise think you are doing anything other than using a global variable. It puts it in a namespace of sorts and protects it to an extent, though the other problems with globals remain. It is generally better not to use this workaround but it may be the right answer for repairing ancient code.
if you want to fully replace them in a large project as a cleanup effort, this can be very difficult. You can use various techniques: declare them in main and pass them down to whoever needs them, for example, works but it can be a giant amount of edits to functions that need an additional parameter now. If that is overwhelming, the class wrapper idea may be useful, or you can try to bundle the functions that need it into a class that has it as a member...
Similar to the class wrapper, you can also use a function wrapper. Here again static is the key, eg
1 2 3 4 5 6 7
|
int &global()
{//this function wraps up a variable that used to be global to the code base.
static int glob;
return glob;
}
then wherever you need it, you can say
int &g = global();
| |
This is sort of the 'letter of the law' problem. You can do it, its terrible, but it solves the 'get rid of the globals' arbitrary code cleanup project with the least amount of time wasted. If you want a better answer, be prepared to do a rewrite or major surgery.