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

标签 c header global-variables constants external

我正在试验 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/

相关文章:

c++ - 赋值 char ** 到 char * 中的类型不兼容

iOS int类型默认值问题

iphone - 如果从上面的部分中删除一行,则该部分下面的标题会重复

C# WebStream 寻求下载 "Chunks"中的文件

c - 执行代码 C 后检索全局变量内容的历史记录

R 列出在某个点之后在全局环境中创建的所有变量

c - 单元测试: CUnit

c - 为什么kiss_fft的正向和反向基4计算不同?

html - 导航菜单栏内的图标放置及其标题的放置问题

javascript - Javascript 中的变量范围(提升)