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

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

问题描述

我正在尝试使用GCC,并发现可以在头文件中声明外部变量 const ,但保留它们在实现文件中可变。



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

  #ifndef HEADER_H_ 
#define HEADER_H_

extern const int global_variable;

#endif

header.c:

  int global_variable = 17; 

这似乎是一个非常好的功能,用于保存 global_variable readonly给 header.h 的用户,但保持它们可以被实现修改( header.c ) 。



注意:下面的代码仅仅是一个例子,说明这种声明如何防止赋值给 global_variable

  #includeheader.h

int main(void )
{
global_variable = 34; / *这是一个错误,因为`global_variable`被声明为const * /
return 0;
}

因为我之前从未见过技术。我开始怀疑它是否有效。



这是明确定义的行为,还是GCC未能提醒我的错误?

解决方案

const int int 不兼容

例如:

  extern const int a; 

int a = 2;

在C中无效,因为C表示:


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


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


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


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



请注意,C90具有相同的段落。

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.

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;

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

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.

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

解决方案

const int and int are not compatible types.

For example this:

extern const int a;

int a = 2;

is not valid in C as C says that:

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

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

(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.

Note that C90 has the same paragraphs.

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

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