栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++:头文件中的const全局变量

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++:头文件中的const全局变量

我们知道,如果否则将全局变量定义在头文件中,然后又在多处include该头文件,会导致全局变量的重复定义,从而无法编译:

//b.h
#ifndef B_H_
#define B_H_

int c_data = 100;    //在头文件b.h中定义了全局变量c_data
void fun_b();

#endif

//--------------------------------------------------------------------

//b.cpp
#include 
#include "b.h"        //导入b.h导致c_data被定义
using namespace std;

void fun_b()
{
	cout<
#include "b.h"        //导入b.h导致c_data被定义
using namespace std;

int main ()
{
	fun_b();
    return 0;
}

由于b.cpp和main.cpp都include了头文件b.h,相当于c_data被定义了两遍
因此导致编译器报错:multiple definition of `c_data'

解决方案是:

在cpp文件中定义全局变量,然后再头文件中对其声明:

//b.h

#ifndef B_H_
#define B_H_

extern int c_data;    //在头文件中声明全局变量
void fun_b();

#endif

//---------------------------------------------------------------------------

//b.cpp
#include 
#include "b.h"
using namespace std;

int c_data = 100;    //在cpp文件中定义全局变量
void fun_b()
{
	cout<
#include "b.h"
using namespace std;

int main ()
{
	fun_b();
    return 0;
}

这一规则有一个例外:如果这个全局变量是const型的,那么可以在头文件中对其进行定义,且不会导致重复定义:

//b.h

#ifndef B_H_
#define B_H_

const int c_data = 100;    //在头文件中定义全局const变量
void fun_b();

#endif

//---------------------------------------------------------------------------

//b.cpp
#include 
#include "b.h"
using namespace std;

void fun_b()
{
	cout<<"in b.cpp "<
#include "b.h"
using namespace std;

int main ()
{
	fun_b();
	cout<<"in main.cpp "< 

事实上,上面的程序之所以能成功编译,是因为对于const全局变量,C++会默认认为其为内部连接,除非将其声明为外部连接:

#ifndef B_H_
#define B_H_

const int c_data = 100;    //将c_data声明为外部连接的全局const变量
void fun_b();

#endif

由于c_data被声明为外部连接,因此不能被多次include到不同的cpp文件,否则编译器会报重复定义

具有外部连接的const全局变量跟普通全局变量一样,需要在cpp文件中定义,并在h文件中对其声明

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934199.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号