Two variables with same name and type, in two different .c files, compile with gcc

自作多情 提交于 2019-11-29 13:38:14

问题


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?


回答1:


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.




回答2:


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)




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/7189982/two-variables-with-same-name-and-type-in-two-different-c-files-compile-with-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!