Possible Duplicate:
Static vs global
I’m confused about the differences between global and static global variables. If static means that this variable is global only for the same file then why in two different files same name cause a name collisions?
Can someone explain this?
Global variables (not
static) are there when you create the.ofile available to the linker for use in other files. Therefore, if you have two files like this, you get name collision ona:a.c:
b.c:
because the linker doesn’t know which of the global
as to use.However, when you define static globals, you are telling the compiler to keep the variable only for that file and don’t let the linker know about it. So if you add
static(in the definition ofa) to the two sample codes I wrote, you won’t get name collisions simply because the linker doesn’t even know there is anain either of the files:a.c:
b.c:
This means that each file works with its own
awithout knowing about the other ones.As a side note, it’s ok to have one of them
staticand the other not as long as they are in different files. If two declarations are in the same file (read translation unit), onestaticand oneextern, see this answer.