gpt4 book ai didi

c - 在全局范围内混合使用 extern、static 和无存储说明符的声明

转载 作者:行者123 更新时间:2023-11-30 19:11:26 24 4
gpt4 key购买 nike

我一直在研究何时可以在全局范围内混合使用 externstatic 和无存储说明符声明的变量。结果让我很困惑。

这是我发现的(每个段落都是一个单独的编译单元):

/* ok */
int x;
int x;

/* ok */
int f();
int f();

/* ok */
int x;
extern int x;

/* ok */
int f();
extern int f();

/* error: static declaration follows non-static declaration */
int x;
static int x;

/* ok (no warning) */
int f();
static int f();

/* ok */
extern int x;
int x;

/* ok */
extern int f();
int f();

/* ok */
extern int x;
extern int x;

/* ok */
extern int f();
extern int f();

/* error: static declaration follows non-static declaration */
extern int x;
static int x;

/* error: static declaration follows non-static declaration */
extern int f();
static int f();

/* error: non-static declaration follows static declaration */
static int x;
int x;

/* ok (no warning) */
static int f();
int f();

/* ok */
static int x;
extern int x;

/* ok */
static int f();
extern int f();

/* ok */
static int x;
static int x;

/* ok */
static int f();
static int f();

我使用 gccclang 得到了相同的结果,但我找不到什么有效、什么无效的模式。

这里面有逻辑吗?

C 标准对于混合使用 externstatic 和无存储说明符声明的全局声明有何规定?

最佳答案

如果您定义的标识符不带关键字static,则它会发布在目标文件中并且可以被其他模块访问。因此,如果您在另一个模块中再次定义不带 static 的标识符,则会发生冲突:两个已发布的标识符。

If you use the keyword static, then (most of) the rest of this doesn't apply.

问题在于声明标识符和定义标识符之间的区别。第一个表示“将有一个具有此类型的标识符 X”。第二个表示“我将把这种类型称为 X”。

  • 使用函数很简单:不提供主体,它只是一个声明。提供主体,它也是一个定义。您可以使用 extern 在头文件中明确说明这一点,但由于它是默认值,因此并不常见。

  • 使用变量就更难了。只需声明变量也定义它 - 因此您可以在定义它的同时初始化它。如果您只想声明它,则需要使用关键字extern - 但您也无法初始化它。你是说“将会有一个名为 X 的变量” - 所以你不能鲁莽地决定它的定义!

这就是为什么在头文件中所有变量都应该显式声明为 externstatic:

  • 第一个是常见的:会有一个每个人都可以访问的公共(public)变量。不要忘记,在 one 模块中的某个地方,您需要提供实际的定义,不带 extern 关键字,并具有可选的初始化值.
  • 第二种情况很少见:包含头文件的每个模块都会有自己的、具有该特定名称的非冲突变量。编译器可能为其分配内存(特别是如果它是常量) - 但如果它确实分配内存,则每个模块中的内存都会不同。你为什么要这样做?也许该头文件的(强制)内联函数需要每个模块都有自己的副本......

关于c - 在全局范围内混合使用 extern、static 和无存储说明符的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com