多文件使用全局变量时extern的规范用法

1 篇文章 0 订阅

      关键字extern用来声明变量或者函数是一个外部变量或者外部函数,也就是说告诉编译器是在其他文件中定义的,编译的时候不要报错,在链接的时候按照字符串寻址可以找到这个变量或者函数。(函数默认是外部类型的,不需要显示声明,但是变量必须,如果想把一个函数声明为只在本文件范围有效,那么可以用static来说明)

      在某个头文件,比如A.h中定义了全局变量比如int a;,那么在其他文件中的函数调用变量a的时候需要在对应头文件或者定义文件中(保证在使用这个变量前)使用extern int a;来声明这个变量,但是这样做有一个弊端,首先如果A.h中集中定义了大量的全局变量供其他文件使用,那么其他的调用文件中会重复的出现大量的extern ***语句,第二,如果其他文件直接引用A.h,那么会造成全局变量的重复定义,编译不过,等等。为了避免上面的种种问题,总结了下extern的使用规范,内容如下:

      1、在定义文件中定义全局变量, 比如A.cpp中定义全局变量 int a;

      2、在对应的头文件A.h中声明外部变量 extern int a;

      3、在引用a变量的文件中包含A.h;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Qt中,多文件全局变量使用可以通过以下几种方式实现: 1. 定义全局变量,在需要使用文件使用extern关键字声明 定义一个全局变量,在一个文件使用,然后在其他文件使用extern关键字声明该变量即可使用: // global.h #ifndef GLOBAL_H #define GLOBAL_H extern int g_value; #endif // global.cpp #include "global.h" int g_value = 10; // main.cpp #include "global.h" #include <iostream> int main() { std::cout << g_value << std::endl; return 0; } 2. 使用单例模式 使用单例模式来创建一个全局变量,可以确保全局变量只被创建一次,同可以方便地在多个文件使用变量: // singleton.h #ifndef SINGLETON_H #define SINGLETON_H class Singleton { public: static Singleton& instance(); int value() const; void setValue(int newValue); private: Singleton(); Singleton(const Singleton&); Singleton& operator=(const Singleton&); int m_value; }; #endif // singleton.cpp #include "singleton.h" Singleton::Singleton() : m_value(0) { } Singleton& Singleton::instance() { static Singleton s; return s; } int Singleton::value() const { return m_value; } void Singleton::setValue(int newValue) { m_value = newValue; } // main.cpp #include "singleton.h" #include <iostream> int main() { std::cout << Singleton::instance().value() << std::endl; Singleton::instance().setValue(10); std::cout << Singleton::instance().value() << std::endl; return 0; } 3. 使用全局变量使用全局变量类可以方便地定义和管理全局变量,同避免了使用全局变量可能出现的一些问题: // globalvariable.h #ifndef GLOBALVARIABLE_H #define GLOBALVARIABLE_H template<typename T> class GlobalVariable { public: static T& instance(); private: GlobalVariable(); GlobalVariable(const GlobalVariable&); GlobalVariable& operator=(const GlobalVariable&); static T m_instance; }; template<typename T> T GlobalVariable<T>::m_instance; template<typename T> T& GlobalVariable<T>::instance() { return m_instance; } #endif // main.cpp #include "globalvariable.h" #include <iostream> int main() { GlobalVariable<int>::instance() = 10; std::cout << GlobalVariable<int>::instance() << std::endl; return 0; } 以上是Qt多文件全局变量使用方法,根据实际需要选择合适的方法即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值