加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C变量定义vs extern decleration

发布时间:2020-12-16 09:59:20 所属栏目:百科 来源:网络整理
导读:这似乎已经涵盖了那类问题,但我似乎无法找到答案. 我遇到过gcc的特殊行为. 我提交A我有以下定义: struct SomeStruct { unsigned int uiVarA; unsigned int uiVarB;} SomeVar; 我提交B extern decleration不同: extern struct SomeStruct { unsigned char f
这似乎已经涵盖了那类问题,但我似乎无法找到答案.

我遇到过gcc的特殊行为.

我提交A我有以下定义:

struct SomeStruct {
  unsigned int uiVarA;
  unsigned int uiVarB;
} SomeVar;

我提交B extern decleration不同:

extern struct SomeStruct {
  unsigned char filler;
  unsigned int uiVarA;
  unsigned int uiVarB;
} SomeVar;

事实上,我可以将定义设为double,extern decleration是一个int,gcc很乐意编译而不需要警告(使用-Wall和-Wextra).

我只能得出结论,这必然意味着它是完全合法的行为但是如此呢?

我知道链接器完成了映射两个变量的工作,但是在这个阶段没有错误检查吗?

解决方法

来自C Spec.

6.2.7 Compatible type and composite type

2 All declarations that refer to the same object or function shall have compatible type; otherwise,the behavior is unde?ned.

因此,行为未定义并非完全合法的行为.但这并不意味着您的链接器能够检查它.它在语法上是正确的(只要每个声明都在不同的翻译单元中).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读