简体   繁体   English

全局静态和局部静态在哪里和何时存储和初始化?

[英]where and when do the global static and local static get stored and initialized?

include 包括

static int i = 10;

int
main()
{
   static int i = 20;

   printf ( "i = %d\n", i );

   return 0;
}

There are two static variables, one in global scope and one in function scope. 有两个静态变量,一个在全局范围内,一个在函数范围内。 The compiler is not throwing "multiple definition" error. 编译器不会引发“多个定义”错误。 Could you please let me know where the two static vars are stored? 您能否让我知道两个静态变量的存储位置?

The two variables are stored separately because they are distinct - it is the compiler's problem to ensure that they are separate. 这两个变量是分开存储的,因为它们是分开的-确保它们分开是编译器的问题。

The variables are both initialized before the program starts - this is C, not C++, where the rules are slightly different. 变量都在程序启动之前初始化-这是C而不是C ++,规则略有不同。

Inside main() as shown, you cannot access the global variable i (again, this is C, not C++). 如图所示,在main()内部,您无法访问全局变量i (同样,它是C,而不是C ++)。

GCC's -Wshadow compiler flag would warn you about the local i shadowing the global one. GCC的-Wshadow编译器标志会发出警告,当地i遮蔽全局的。

These variables are called "symbols", and during compiling a table is generated, the "symbol table". 这些变量称为“符号”,在编译表时会生成“符号表”。 This table contains the name, type, scope and memory pointer to each symbol (this is like the minimum, you usually have a bunch of more stuff), and each time a reference is made to an symbol in a specific scope, it's substituted for an index into the table. 该表包含名称,类型,作用域和指向每个符号的内存指针(就像最小符号一样,您通常会有很多东西),并且每次在特定作用域中对符号进行引用时,它都会被替换表的索引。 These indices are unique, so is the combination of name+scope. 这些索引是唯一的,名称和范围的组合也是唯一的。

So in short, the names of the variables are simply decoration, internally the compiler works with a symbol table and indices into it. 简而言之,变量的名称只是修饰,内部编译器使用符号表并对其进行索引。 Statics are initialized during program startup by iterating through a table of pointers to them and putting the correct values in place. 在程序启动期间,通过遍历指向它们的指针表并将正确的值放在适当的位置来初始化静态函数。

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

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