wef*_*fa3 7 c header constants external global-variables
我正在试验GCC,发现你可以const在头文件中声明外部变量,但在实现文件中保持它们是可变的.
编辑:这实际上不起作用.我编译测试代码的唯一原因是因为我没有在"header.c"中包含"header.h".
header.h:
#ifndef HEADER_H_
#define HEADER_H_
extern const int global_variable;
#endif
Run Code Online (Sandbox Code Playgroud)
header.c:
int global_variable = 17;
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常好的功能,用于保持global_variablereadonly给用户,header.h但保持它们可以通过implementation(header.c)进行修改.
注意:以下代码只是这种声明方式如何阻止赋值的示例global_variable.
#include "header.h"
int main(void)
{
global_variable = 34; /* This is an error as `global_variable` is declared const */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为我之前从未见过技术.我开始怀疑它是否有效.
这是一个定义明确的行为还是这是GCC未能提醒我的错误?
const int并且int不兼容类型.
例如:
extern const int a;
int a = 2;
Run Code Online (Sandbox Code Playgroud)
在C中无效,因为C表示:
(C11,6.7p4)"同一范围内涉及同一对象或功能的所有声明均应指定兼容类型"
在你的情况下,他们不在同一范围(不同的翻译单位),但C也说:
(C11,6.2.7p2)"所有引用相同对象或函数的声明都应具有兼容类型;否则,行为未定义."
当您违反上述规则时,您正在调用未定义的行为.
请注意,C90具有相同的段落.