Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

static

gcc

extern

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?

like image 705
Ivan Š Avatar asked Aug 25 '11 12:08

Ivan Š


3 Answers

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.

like image 60
cnicutar Avatar answered Nov 12 '22 13:11

cnicutar


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.

like image 42
user2858081 Avatar answered Nov 12 '22 12:11

user2858081


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)

like image 4
Abraham Avatar answered Nov 12 '22 13:11

Abraham