#关于全局变量的理解与头文件、extern的综合运用

写在前面:借写课程大作业的时候,摆脱平常只写百来行代码的局限,尝试使用头文件使代码条理更清晰。结果发现想象中.cpp的“全局”并非实际的项目的全局。折腾了许久,得到此篇收获总结。

问题描述:

为了减少小游戏编程中函数复杂的参数传递,在.cpp文件中定义了如下“个人自以为是全局变量”的变量

/*********************全局变量***************************/

struct Player player[Playernum];//两个玩家
struct Shell shell[Playernum];//两个玩家的武器
struct Wind wind;//风力与风向
int turn;//玩家轮回
int GameMode;////游戏模式选择 0为普通对战 1为无尽模式

 /*----------无尽模式 ---------------*/
IMAGE enemy_pic;//ai的图片
IMAGE enemy_pic_mask;//ai的图片掩码
List Leftlist, Rightlist;//无尽模式下ai链表

/*---------- micro map ---------------*/

IMAGE	GPS_image;					// 迷你地图,用于显示游戏者在地图中的位置
POINT	 GPS_position[2];					// 迷你地图中玩家的显示位置
SIZE	GPS_size;					// 迷你地图的尺寸

并希望在.h头文件定义的函数中对.cpp定义变量进行调用。

结果发生如下报错:


扫描二维码关注公众号,回复: 1483822 查看本文章

解决方案:

在.h头文件中进行外部变量extern的声明

/*********************全局变量***************************/

extern struct Player player[Playernum];//两个玩家
extern struct Shell shell[Playernum];//两个玩家的武器
extern struct Wind wind;//风力与风向
extern int turn;//玩家轮回
extern int GameMode;////游戏模式选择 0为普通对战 1为无尽模式

/*----------无尽模式 ---------------*/
extern IMAGE enemy_pic;//ai的图片
extern IMAGE enemy_pic_mask;//ai的图片掩码
extern List Leftlist, Rightlist;//无尽模式下ai链表

/*---------- micro map ---------------*/

extern IMAGE	GPS_image;					// 迷你地图,用于显示游戏者在地图中的位置
extern POINT	 GPS_position[2];					// 迷你地图中玩家的显示位置
extern SIZE	GPS_size;					// 迷你地图的尺寸
/*********************************************************/
 
 

个人理解:

在.cpp中,main函数之外定义的变量,eg. int player; 

也就是个人此前所理解的“全局变量”,其作用域是整个.cpp。所以对于只包含一个.cpp的小程序而言,堪称“全局”;

但.cpp中声明的变量作用域不包含外部文件,即.h头文件中不存在 上述定义的变量player。故要想在.h中调用player,需要在.h中进行extern int player ; 的声明。从而实现对其的调用。

另外,extern的主要两个功能概述如下:

1.外部引用其他文件定义的变量;2.在变量实际定义之前进行声明引用;

详见:


  • The rules for using extern are:

  • The extern storage-class specifier declares a reference to a variable defined elsewhere. You can use an extern declaration to make a definition in another source file visible, or to make a variable visible prior to its definition in the same source file. Once you have declared a reference to the variable at the external level, the variable is visible throughout the remainder of the translation unit in which the declared reference occurs.

  • For an extern reference to be valid, the variable it refers to must be defined once, and only once, at the external level. This definition (without the extern storage class) can be in any of the translation units that make up the program.


猜你喜欢

转载自blog.csdn.net/weixin_40505645/article/details/80569681
今日推荐