当前位置:网站首页>声明为全局变量
声明为全局变量
2022-04-23 05:48:00 【老朽在门外】
声明为全局变量
C++中定义全局变量是应该尽量在.cpp文件中定义,而不要在.h 文件中 定义,定义好了之后,可以在.h文件中利用extern关键字进行声明。如果在.h文件中定义的话,多层包含可能会引起重复定义的错误。下面是一个示例:
在g_bash.cpp中定义全局变量:
// g_bash.cpp
#include “g_base.h”
int g_TicketCount = 0; // 定义全局变量并初始化
在g_bash.h文件中利用extern关键字进行声明:
// g_bash.h
#ifndef G_BASE_H
#define G_BASE_H
extern int g_TicketCount; // 全局变量声明
#endif // G_BASE_H
然后在其他文件要使用这些变量的时候,只要#include "g_base.h"就可以了,而且不会引起重复定义的错误。main.cpp下引用示例:
#include
#include
#include g_base.h
extern int g_TicketCount; // 全局变量声明
using namespace std;
void proc()
{
cout<< proc(): <<endl;
g_TicketCount++;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<< g_TicketCount = << g_TicketCount << endl;
proc();
cout<< g_TicketCount = << g_TicketCount << endl;
return a.exec();
}
https://www.jb51.net/article/224822.htm
版权声明
本文为[老朽在门外]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_41167925/article/details/124310128
边栏推荐
- 【UDS统一诊断服务】四、诊断典型服务(1)— 诊断和通信管理功能单元
- Friend function, friend class, class template
- C语言的运算符
- Record the installation and configuration of gestermer on TX2, and then use GST RTSP server
- Rust 中的指针:Box、Rc、Cell、RefCell
- SQL -- data filtering and grouping
- GDB debugger installation and use
- Busybox initrd and initialization process
- MySQL groups are sorted by a field, and the first value is taken
- [untitled] database - limit the number of returned rows
猜你喜欢

基于Sentinel+Nacos 对Feign Client 动态添加默认熔断规则

MySQL groups are sorted by a field, and the first value is taken

Motor and drive (Qi Jinqing Edition)

Call procedure of function

7-21日错题涉及知识点。

Detailed arrangement of knowledge points of University probability theory and mathematical statistics

Vscode custom comments

【UDS统一诊断服务】四、诊断典型服务(2)— 数据传输功能单元

Basic knowledge of network in cloud computing

搭建jpress个人博客
随机推荐
爬取手游网站游戏详情和评论(MQ+多线程)
Busybox initrd and initialization process
C#【文件操作篇】PDF文件和图片互相转换
[untitled]
相机标定:关键点法 vs 直接法
对象数组与对象指针
用C语言实现重写strcmp等四个函数
基于QQwebAPI 查询昵称和头像的爬虫
Swagger2 generates API documents
Rust: Tcp 服务器与客户端的一个简单例子
Gesture recognition research
Rust 中的 RefCell
日志
How SYSTEMd uses / etc / init D script
Vscode custom comments
用二进制进行权限管理
serde - rust的序列化方案
数组旋转
词频统计
C语言循环结构程序