VC+++ 全局变量的定义

来源:百度知道 编辑:UC知道 时间:2024/05/17 04:52:07
假如我现在有N个文件 问我要定义一个全局变量在哪定义啊
最好写下
我也知道啊,可是提示:我别的什么也没有加啊 ,怎么回事啊
c:\documents and settings\administrator\桌面\newdicom3.0070516\newdicom\stdafx.h(11) : error C2146: syntax error : missing ';' before identifier 'str11'
c:\documents and settings\administrator\桌面\newdicom3.0070516\newdicom\stdafx.h(11) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\administrator\桌面\newdicom3.0070516\newdicom\stdafx.h(11) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

全局变量最好是“定义”在一个单独的.cpp源文件中,然后再在一个.h头文件中进行“声明”。注意定义和声明的不同。

定义要在源文件中,写:
int a;
声明则在头文件中,写:
extern int a;

stdafx.h是VC机器生成的文件,不推荐修改它,最好还是单独写一个头文件。在且只在所有引用这些全局变量的地方包含这个头文件。

全局变量一般这样定义:
1。在一类的.cpp中定义 int myInt;然后再在要用到的地方的.cpp里extern int myInt。
2。在stdafx.cpp中加入:int myInt;然后在stdafx.h中加入:extern int myInt
3。先定义一个Glbs.h,把所有的全局变量原始定义放进去。然后定义一个Externs.h,把先前定义在Glbs.h中的变量都加上extern。注意:如果你在Glbs.h中设置了初值,那么在Externs.h中就不要加值了。然后调用时,第一次调用的#i
nclude <Glbs.h>,以后调用的#i nclude <Externs.h>
4.在CApp中定义变量:CString g_sUser;//定义全局
在要引用的类中如此:extern CSvApp theApp;//加入 这句.在.CPP文件的构造函数前.
在引用时:if( theApp.m_sUserName == "") ;//这样引用.
5.如果要使用自定义的全局自定义类一般如下方法,可使在所有文件中都可以使用。
一,在stdafx.h中加入类的头文件
二,在stdafx.cpp中加入类的定义 如:CMyClass g_class;
三,在你程序的app类中,如果CTestProjectApp类的头文件的开头处加上 extern CMyClass g_clas。

工程中随便一个文件的非函数体内都可以,引用时extern就行了.
一般按负家的方法,放在stdafx.h,毕竟是大部分文件都会引用的.

在stdafx.h里面定就行了。要引用它的地方加一