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
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With