我正在试验 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_variable
对 header.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 int
和 int
是不兼容的类型。
例如这个:
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/