普通 C 中的静态变量和 extern
在函数外部声明静态变量和在函数内部声明静态变量有区别吗?
另外,将变量声明为静态变量和仅声明外部变量有什么区别?
Is there a difference between declaring a static variable outside of a function and declaring a static variable inside a function?
Also, what's the difference between declaring a variable as static and just declaring an extern variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同之处在于,函数内部的静态变量仅在函数内部可见,而外部的静态变量可以被任何函数从其声明点到翻译单元末尾看到。
否则,他们的行为是一样的。
在函数外部声明一个变量而不使用关键字
static
意味着它在定义该变量的文件(翻译单元)外部(以及从定义点到该变量的末尾)是可见的(可访问的)。翻译单位)。如果将变量声明为 extern,则意味着在其他地方有定义 - 可能在同一个翻译单元中,但更有可能在另一个翻译单元中。请注意,可以在函数内部声明 extern 变量,但只能在函数外部定义它。The difference is that the static variable inside the function is visible inside the function only, whereas the static variable outside may be seen by any function from its point of declaration to the end of the translation unit.
Otherwise, they behave the same.
Declaring a variable outside of a function without the keyword
static
means it is visible (accessible) outside the file (translation unit) where it is defined (as well as from the point of definition to the end of the translation unit). If you declare a variable asextern
, it means that there is a definition somewhere else - possibly in the same translation unit, but more likely in another. Note that it is possible to declare an extern variable inside a function, but it can only be defined outside of a function.第一个例子:
产生:
现在你的问题
这些是完全不同的问题
函数外的静态变量/函数在编译单元之外不可见。
函数内部的静态变量在全局数据中分配,并且在第一次出现时仅初始化一次(请参阅 FunctionStaticObj 在 main 之后初始化,这与其他对象相矛盾。
同样,静态意味着在编译单元外部不可见。
extern 的意思是“它没有在这里定义,尽管在不同的编译单元中,并且链接器会管理它”,因此您可以根据需要创建任意多个外部声明,但只能创建一个非外部定义。
First Example:
produces:
Now your question(s)
Those are completely different issues
static variable / function outside function is not visible outside compilation unit.
static variable inside function is allocated in global data and is initialized only once during first occurance (see that FunctionStaticObj was initialized after main in contradiction to other objects.
Again static means not visible outside compilation unit.
extern means "it's not defined here, although in different compilation unit and linker will manage it" so you can make as many extern declarations as you want but only one non extern definition.