C 语言全局变量

yingyong.c

int yueqiu;
void sub_fun(void)
{
    yueqiu = 2;
    printf("sub yueqiu = %d\n", yueqiu);
}
main.c
int yueqiu;
void sub_fun(void);
int main(int argc, char *argv[])
{
    yueqiu = 1;
    printf("main yueqiu = %d\n", yueqiu);
    sub_fun();
    return 0;
}

打印结果:

main yueqiu = 1
sub yueqiu = 2

C和C++中是不一样的
C中可能会被当做声明,而C++中肯定是定义 不同的编译器效果不一样?
Object declaration at file scope

  Note  

      In C++, a declaration of an object at file scope without a  
      storage class specifier is a definition of that object  
      with external linkage.  If the definition does not have an  
      initializer, the object has initial value 0.  (As in C, an  
      object declared in a C++ program must be defined exactly  
      once.)  

      In C, a declaration of an object at file scope without a  
      storage class specifier and without an initializer is a  
      tentative definition, which may appear more than once in a  
      translation unit.  

  Example  

      int a;          /* (1) */  
      int a = 10;     /* (2) */  

      In C, (1) is a tentative definition.  Since (2) is  
      unequivocally a definition, C treats (1) as a mere  
      declaration.  

      In C++, both (1) and (2) are definitions.  In the  
      presence of (1), (2) is a duplicate definition, and  
      therefore an error

另外,<<深度探索对象模型>>page197
因为int a;没有明确的初始化操作,所以a被视为一个"临时性的定义",可以在程序中发生多次
那些实例会被连接器折叠起来,只留一个单独的实体

若是 int yueqiu = 3; 即为一个实体,若在另一个文件中又 int yueqiu = 4; 则构成重复定义,同理包含同一个头文件(int yueqiu = 5),也会构成重复定义

c++多个文件中如何共用一个全局变量

 

转载于:https://my.oschina.net/u/592470/blog/1546497

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值