Ivan Š
Ivan Š

Reputation: 1032

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

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?

Upvotes: 15

Views: 14273

Answers (4)

Abraham
Abraham

Reputation: 41

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)

Upvotes: 4

user2858081
user2858081

Reputation: 21

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.

Upvotes: 2

Ottavio Campana
Ottavio Campana

Reputation: 4168

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

Upvotes: 1

cnicutar
cnicutar

Reputation: 182629

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.

Upvotes: 29

Related Questions