为什么此代码中的 `bar` 没有静态存储持续时间?

Why doesn't `bar` in this code have static storage duration?

代码在前:

#include <stdio.h>

void foo()
{
        static int bar;
}

int main()
{
        bar++;
        return 0;
}

编译器 (Clang) 抱怨:

static.c:10:2: error: use of undeclared identifier 'bar'

foo()中的语句static int bar;不应该给出bar静态存储持续时间,使其在main函数之前声明和初始化吗?

在函数中将某些内容标记为 static 会将其存储重新定位到堆栈之外,并允许其值在多次调用中保持不变。

但是,标记某些东西 static 不会改变变量的范围。虽然您当然可以创建一个指向 bar 的指针并从 main 对其进行操作,但由于作用域的原因,编译器会将 bar 视为 main 中的未定义。

您混淆了变量的 范围 存储持续时间

C11 标准第 6.2.1 章所述,标识符范围

  • 对于文件范围

[...] If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. [...]

函数(或)作用域

[...] If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. [...]

在您的例子中,bar 的文件范围在 foo() 中。所以这在 main().

visible

OTOH,对于存储持续时间部分,

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

所以,总结一下,bar有静态存储时长,但范围仅限于foo()函数。所以,是

declared and initialized prior to main() function

(确切地说,在 main() 开始之前)但在 main().

中不可见和不可访问