有人问特整理出来
1
.
对于全局变量存在和函数一样的问题,为了在其他CPP文件中能够访问这些变量,必须在主文件的H文件中加上extern声明,格式如下:
extern
varibletype var;
在主文件的CPP文件中定义
varibletype var;
例子:
AppWizard建立一个Test工程
那么在Test.h中声明extern CString cs;
在Test.app定义CString cs;
2
.应用程序类的主头文件处定义变量varibletype var,然后,在程序的任何地方,都可以用下面的方法来访问该变量:
CClassApp
*
app
=
(CClassApp
*
)AfxGetApp();
app
->
var
=
类似的,以上方法也可以定义全局对象
例子:
AppWizard建立一个Test工程
那么在Test.h中声明 CString cs;
使用的时候CTestApp
*
app
=
(CTestApp
*
)AfxGetApp();
app
->
cs
=
"
Global
"
![None.gif](/Images/OutliningIndicators/None.gif)
防错措施:
若定义的函数和全局变量在多个文件包含且造成嵌套或多次调用的话,这样将导致这个头文件每被包含依次,函数或变量就被重新定义一次,在链接编译时会导致重定义错误。为此需要使用一种被称为Guard macro的技术来保证不出错。在一个头文件开头加上
#ifndef _MACRO_1_
#define
_MACRO_1_
在文件末尾增加
#endif
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)