gpt4 book ai didi

c - 在头文件中声明全局变量 `extern const int` 但在源文件中仅声明 `int`

转载 作者:太空狗 更新时间:2023-10-29 17:09:56 26 4
gpt4 key购买 nike

我正在试验 GCC,发现您可以在头文件中声明外部变量 const,但在实现文件中保持它们可变。

编辑:这实际上不起作用。我编译测试代码的唯一原因是我没有在“header.c”中包含“header.h”。

标题.h:

#ifndef HEADER_H_
#define HEADER_H_

extern const int global_variable;

#endif

header.c:

int global_variable = 17;

这似乎是一个很好的特性,可用于保持 global_variableheader.h 的用户只读,但保持它们可由实现(header.h)修改。 c).

注意:以下代码只是一个示例,说明这种声明方式将如何阻止对 global_variable 的赋值。

#include "header.h"

int main(void)
{
global_variable = 34; /* This is an error as `global_variable` is declared const */
return 0;
}

因为我从来没有在实践中见过技术。我开始怀疑它是否有效。

这是定义明确的行为还是 GCC 未能警告我的错误?

最佳答案

const intint 是不兼容的类型。

例如这个:

extern const int a;

int a = 2;

在 C 中无效,正如 C 所说:

(C11, 6.7p4) "All declarations in the same scope that refer to the same object or function shall specify compatible types"

在您的情况下,它们不在同一范围内(不同的翻译单元),但 C 也表示:

(C11, 6.2.7p2) "All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined."

由于您违反了上述规则,您正在调用未定义的行为。

注意C90有相同的段落。

关于c - 在头文件中声明全局变量 `extern const int` 但在源文件中仅声明 `int`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27724453/

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