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

Ivan Š picture Ivan Š · Aug 25, 2011 · Viewed 9.6k times · Source

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?

Answer

cnicutar picture cnicutar · Aug 25, 2011

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.