两个变量具有相同的名称和类型,在两个不同的.c文件,用gcc编译 [英] Two variables with same name and type, in two different .c files, compile with gcc

查看:452
本文介绍了两个变量具有相同的名称和类型,在两个不同的.c文件,用gcc编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的交易。我在两个不同的.c文件有两个相同的全局变量,他们不声明为extern。因此,每个.c文件应该已经看到了自己的变量,对吧?

不过,我已经得到了一些非常奇怪的行为,因为如果一个文件被读取其他文件变量(连接在一起后)。添加静态预选赛两个变量定义似乎解决了这个问题。

那么,实际上,我想是,到底发生了什么有没有静态预选赛?


解决方案

  

因此​​,每个.c文件应该已经看到了自己的变量,对吧?


错误。在C语言中,省略静态从声明意味着隐含的的extern 联动。

从C一言以蔽之:


  

,编译器将函数声明没有存储类
  说明,如果他们包括说明EXTERN。同样,任何
  你声明之外的所有功能和无对象标识符
  一个存储类说明有外部链接


Here's the deal. I've had two identical global variables in two different .c files, they weren't declared as extern. So each .c file should have seen its own variable, right?

But I have gotten some really strange behaviour, as if one file was reading the other files variable (after linking them together). Adding 'static' qualifier to both variables definitions seemed to fix this issue.

So what I'm actually wondering is, what exactly happened there without the 'static' qualifier?

解决方案

So each .c file should have seen its own variable, right?

Wrong. In C, omitting static from a declaration means implicit extern linkage.

From C In a Nutshell:

The compiler treats function declarations without a storage class specifier as if they included the specifier extern. Similarly, any object identifiers that you declare outside all functions and without a storage class specifier have external linkage.

这篇关于两个变量具有相同的名称和类型,在两个不同的.c文件,用gcc编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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