简体   繁体   English

C中的全局静态变量和局部静态变量如何不会发生冲突

[英]How global static and local static variables in C won't clash

I have a global static variable 'x' defined in my program and I have local static variable 'x' defined in one function of same program. 我在程序中定义了全局静态变量“ x”,而在同一程序的一个函数中定义了局部静态变量“ x”。 Both should be residing in Data segment. 两者都应位于数据段中。 Then why the compiler is not giving error or how the names are resolved. 然后为什么编译器没有给出错误或如何解析名称。

You are correct that both variables will be stored in the Data segment. 您将两个变量都存储在“数据”段中是正确的。 However, these values are simply stored in two different offsets in that segment. 但是,这些值仅存储在该段中的两个不同偏移中。 The compiler differentiates between these two variables using scope, and based on that it converts it into the right offset. 编译器使用范围来区分这两个变量,并基于此将其转换为正确的偏移量。

why the compiler is not giving error 为什么编译器没有给出错误

Because those two variables have different scope, which means they are two different variable from the viewpoint of a compiler. 因为这两个变量的作用域不同,所以从编译器的角度来看,这是两个不同的变量。

how the names are resolved 名称如何解析

Compiler may give them different names. 编译器可能会给他们使用不同的名称。

For example 例如

static int x;

void foo(void) {
    static int x;
}

here is the symbols for both x : 这是x的符号:

$ readelf -s t108.o | grep x
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
     6: 0000000000000004     4 OBJECT  LOCAL  DEFAULT    3 x.1707

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM