Why won't extern link to a static variable?

前端 未结 4 572
离开以前
离开以前 2020-11-29 16:51

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 thes

4条回答
  •  清酒与你
    2020-11-29 17:19

    In standard C, there are two scopes for variables declared outside of a function. A static variable is only visible inside the compilation unit (i.e., file) that declared it, and non-static variables are visible across the whole program. An extern declaration says that the variable's location isn't known yet, but will be sorted out by the linker; it's compatible with non-static variables, but extern static is just crazy talk!

    Of course, in practice there are other visibilities these days. In particular, there are now scoping levels between that of a single source file and a whole program; the level of a single shared library is a useful one (settable through mechanisms like GCC function attributes). But that's just a variation on the theme of non-static variables; static keeps the same interpretation it had before.

提交回复
热议问题