在标头中声明全局变量“extern const int",但在源文件中仅声明“int" [英] Declaring a global variable `extern const int` in header but only `int` in source file

查看:9
本文介绍了在标头中声明全局变量“extern const int",但在源文件中仅声明“int"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用 GCC 做实验,发现你可以在头文件中声明外部变量 const 但在实现文件中保持可变.

I was experimenting with GCC and found out that you can declare external variables const in header files but keep them mutable in implementation files.

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

EDIT: This does actually not work. The only reason I got my test code to compile was because I did not include "header.h" in "header.c".

header.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).

This seems like a very good feature to use for keeping global_variable readonly to the users of header.h but keeping them modifable by the implementation (header.c).

注意:以下代码只是说明这种声明方式如何防止分配给 global_variable 的示例.

NOTE: The following code is just an example on how this way of declaring will prevent assignment to global_variable.

#include "header.h"

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

因为我以前从未在实践中看到过技术.我开始怀疑它是否有效.

Because I have never seen technique in practise before. I start to wonder if it is valid.

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

Is this well defined behaivor or is this an error that GCC fails to warn me about?

推荐答案

const intint 不是兼容的类型.

const int and int are not compatible types.

例如:

extern const int a;

int a = 2;

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

is not valid in C as C says that:

(C11, 6.7p4) "同一范围内引用同一对象或函数的所有声明应指定兼容类型"

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

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

In your case they are not in the same scope (different translation units) but C also says that:

(C11, 6.2.7p2) "所有引用同一对象或函数的声明都应具有兼容的类型;否则,行为未定义."

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

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

As you are violating the rule above, you are invoking undefined behavior.

请注意,C90 有相同的段落.

Note that C90 has the same paragraphs.

这篇关于在标头中声明全局变量“extern const int",但在源文件中仅声明“int"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆