两个不同名称和类型的变量,在两个不同的.c文件中,用gcc编译
事情是这样的。我在两个不同的 .c 文件中有两个相同的全局变量,它们没有声明为 extern。所以每个 .c 文件应该看到自己的变量,对吧?
但我得到了一些非常奇怪的行为,就好像一个文件正在读取其他文件变量(将它们链接在一起之后)。向两个变量定义添加“静态”限定符似乎可以解决此问题。
所以我实际上想知道的是,如果没有“静态”限定符,到底发生了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
错误的。在 C 中,从声明中省略
static
意味着隐式extern
链接。简而言之,来自 C:
Wrong. In C, omitting
static
from a declaration means implicitextern
linkage.From C In a Nutshell:
始终初始化全局变量,然后编译器不会自动将其链接视为外部。编译器在编译过程中会抛出错误。
这将有助于避免大型代码库中的随机问题,因为我们的代码可能使用其他人声明的具有一些随机值的变量(从我们的逻辑角度来看)
ALWAYS initialize global variable, then compiler will not consider its linkage automatically as extern. Compiler will throw error during compilation.
This will help to avoid random problems in big code base ,because our code may use somebody else declared variable that has some random value (in our logic perspective)
输出文件是通过创建单独文件的目标文件,然后通过链接器将它们链接在一起来生成的。现在,当您在两个不同的文件中有相同的变量时,单个文件将编译而不会出现错误,但在链接时链接器将获得变量的两个定义并生成错误。但是,在两个变量的静态范围仅限于文件的情况下,一切都正常。
我希望您会发现这很有用。
output file is generated by making object file of individually file and then linking them together by linker. Now when you have identical variable in two different file then individual file will compile with no error but at time of linking linker will get two definition of variable and generate an error. But In the case of static scope of both variable limited for the file so, every things works fine.
I hope you will find this useful.
据我所知,当您既不指定 static 也不指定 extern 时,则由编译器来选择。在这种情况下,gcc 适用于 extern,因此您必须在您的情况下指定 static。
几年前我也遇到过同样的问题:-)
As far as I know, when you do not specify neither static nor extern then it's up to the compiler to choose. And gcc in this case goes for extern, thus you have to specify static in your case.
I had the same problem, a few years ago :-)