在C ++程序中删除全局变量 [英] remove global variables in c++ program

查看:208
本文介绍了在C ++程序中删除全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中有一个大型程序,具有太多的函数和全局变量。现在,我想删除那些全局变量,并且只想使用局部变量,而不要使用全局变量。谁能建议我这样做的最好方法。
谢谢!

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!

在C ++中大约有4000行代码。在这些不同的类中有10个类和60个函数,以及30个全局变量。全局变量已在不同类的函数之间使用。

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.

推荐答案

我通常首先将全局变量放在命名空间中

I normally start by putting the global variables in a namespace

namespace global
{
  int var;
  ...
}

这将使您到处都出错使用'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 ) ...

现在通过搜索 global :: var 您会获得一个使用变量的列表,然后您需要逐个查看使用情况,以查看变量是否在多个模块中使用,在这些情况下,您可能需要

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.

这篇关于在C ++程序中删除全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆