为什么不会的extern链接到一个静态变量? [英] Why won't extern link to a static variable?

查看:101
本文介绍了为什么不会的extern链接到一个静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么n被宣布时,的extern INTñ不能编译(在不同的文件中)静态INTñ,但是当宣布工程 INTñ? (这两个声明都是在文件范围内。)

Why does extern int n not compile when n is declared (in a different file) static int n, but works when declared int n? (Both of these declarations were at file scope.)

基本上,这是为什么 INTñ文件范围不在同一范围内一样静态INTñ?难道只有在关系为extern?如果是这样,我失去了约的extern什么?

Basically, why is int n in file scope not the same as static int n in the same scope? Is it only in relation to extern? If so, what about extern am I missing?

推荐答案

整和的全部目的静态是声明一个变量的私有的它在宣布的源文件。因此,在做precisely它的工作在preventing从一个外部的连接。

The whole and entire purpose of static is to declare that a variable is private to the source file that it is declared in. Thus, it is doing precisely its job in preventing a connection from an extern.

请记住,有文件作用域的变量定义的四种口味:

Keep in mind that there are four flavors of file-scope variable definition:


  1. INT等等= 0; - 嗒嗒在此文件中定义,并从其他文件访问。在其他文件中的定义是重复的,并会导致错误。

  2. 的extern INT等等。 - 嗒嗒必须在别处定义,并从该文件中引用

  3. INT等等; - 这是FORTRAN COMMON 的道德等价物。你可以在文件中任意数量的这些,而且都是由链接器解析为一个共享 INT 。 (*)

  4. 静态INT等等; (任选与初始化) - 这是静态的。这是完全私有的文件。这是在其他文件实习医生不可见,你可以有许多不同的文件,所有的申报静态类型等等; ,而且都是不同的

  1. int blah = 0; — blah is defined in this file and accessible from other files. Definitions in other files are duplicates and will lead to errors.
  2. extern int blah; — blah must be defined elsewhere and is referenced from this file.
  3. int blah; — This is the moral equivalent of FORTRAN COMMON. You can have any number of these in files, and they are all resolved by the linker to one shared int. (*)
  4. static int blah; (optionally with an initializer) — This is static. It is completely private to this file. It is not visible to externs in other files, and you can have many different files that all declare static TYPE blah;, and they are all different.

有关在观众较真:'文件'=的编译单元

For the purists in the audience: 'file' = compilation unit.

需要注意的是静态函数内(而不是在文件范围),甚至更紧密范围:如果两个函数声明静态INT的Bleh = 0; 即使在同一个文件时,他们无关。

Note that static inside functions (not at file scope) are even more tightly scoped: if two functions declare static int bleh = 0; even in the same file, they are unrelated.

(*):对于那些你不熟悉:在通常的模式,一个编译单位必须定义一个全局变量,和其他人可以参考它。它在编译单元的生活。在情况(3),上面没有文件(或所有文件)定义它。如果两个文件说 INT等等= 0; ,链接器会抱怨的多个定义。如果两个文件说 INT等等; 链接器乐呵呵地创建一个单一的全球 INT 并导致所有code到参考一下吧。

(*): for those of you not familiar: in the usual pattern, one compilation unit has to define a global variable, and others can reference it. It 'lives' in that compilation unit. In case (3), above, no file (or all the files) defines it. If two files say int blah = 0;, the linker will complain of multiple definitions. If two files say int blah; the linker cheerfully creates a single global int and causes all the code to refer to it.

这篇关于为什么不会的extern链接到一个静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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