多个文件中的全局变量 [英] global variable in multiple files

查看:115
本文介绍了多个文件中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

global.cpp:

global.cpp:

int global = 0;
int world = 0;


global.h:


global.h:

#ifndef GLOBAL_H
#define GLOBAL_H

extern int global;
extern int world;


#endif


main_1.cpp:


main_1.cpp:

#include "global.h"

int main1()
{ 
  set global = 1;  //read the value "1" from one device;

  get world;  // use world to do sth

}


main_2.cpp:


main_2.cpp:

#include "global.h"

int main2()
{
  set world = 222; //read the value "222" from another device

  get global;     //use global to do sth;
  }



-------------------------------------------------

对于文件main_2.cpp中的global值和文件main_1.cpp中的world值,我有些怀疑.我期望世界或全局值可以通过不同的函数进行存储和更新.



-------------------------------------------------

I m a bit doubtful about what is the value of global in file main_2.cpp and the value of world in file main_1.cpp. What I expect is that the value of world or global can be stored and updated by different function.

推荐答案

在您的示例中,只有一个且只有一个名为全球的". 世界"也是如此.根据您的声明,所有访问者通常都共享这些声明.

Main_2.Cpp中"global"的值完全取决于您未指定的函数main1()和main2()的执行顺序.

如果我们假设函数按main1()然后main2()的顺序完成,则global的值为1(在main1()中设置),而不是0(在globals.cpp的静态初始值设定项中设置). ).

明白了吗?
In your example, there is one and only one variable named "global". Same goes for "world". By your declarations, those are commonly shared by any and all accessors.

The value of "global" in Main_2.Cpp totally depends on the execution order of the functions main1() and main2(), which you didn''t specify.

If we are to assume the functions are done in the order of main1() and then main2(), the value of global is 1 (as set in main1()) and not 0 (as set in the static initializer of globals.cpp).

Got it?


这篇关于多个文件中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆