How to define global variable MFC 中全局变量的定义

本文介绍了如何在C++项目中定义和使用全局变量的方法。通过在.cpp源文件中定义全局变量并在对应的.h头文件中声明该变量为外部变量的方式,使得全局变量能够在项目的多个类中被访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.We could define a global variable in Stafx.h.

2.But for the sake of readability,Open two files in Notepad,save as .cpp(source file) and .h(header file) files,in the .cpp file we define the global variable ,in .h declare as external variable,and include the .h header file in the required class .
eg:

In Globalsv.cpp // this is the .cpp file

#include "Globalsv.h" //include the header file
int gv; //define the global variable here

In Globalsv.h declare the external variable
extern int gv; //this is the .h file and we declare the external variable here
and then,and don't forger to add Globalsv.h and Globalsv.cpp to the project.

At last you can use the global variable gv in any class you want to by including the header file Globalsv.h in your class.

 

chinese:

 

1可以在stdafx.h中定义

2但为了可读性,可以打开两个记事本,分别保存为.cpp和.h文件,在.cpp中定义,在.h中声明为外部变量,在所需要的类中包含.h头文件
eg:

在Globalsv.cpp中
#include "Globalsv.h"
int gv;

在Globalsv.h中声明为外部变量
extern int gv;

然后,将Globalsv.cpp和Globalsv.h添加到工程,
然后就可以在任意你想用变量gv的类的前面包含Globalsv.h

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值