The following program was on a practice worksheet given out in class. We are asked to give its output, but from what I understand about linkage, file2.c should not have two
The compiler creates a different instance for every global static variable, even when you have several such variables with identical names.
In fact, the compiler (or possibly, the preprocessor) implicitly changes the name of every such variable, according to the name of the source file which declares it.
You can prove this to yourself by declaring a global static variable in a header file, and then include this header file in several different source files. Try to set it to a different value in each source file, and you'll see that this variable retains its different value in each source file.
If you want to have the same instance of a global variable accessible in several source files, then you should refrain from declaring it static
:
extern
as prefix, and include the header file in every source file that makes use of this variable.extern
in every other source file that makes use of this variable.The address of an external global variable is determined only during linkage. This is in contrast with the following cases, in which the address of the variable is determined during compilation:
I believe that the term static linkage
refers to the linkage of compiled objects (or libraries) into the executable image during the build process, as opposed to dynamic linkage
which refers to the linkage of compiled code (also known as DLL) into the executable image only during runtime.
UPDATE:
After reading your clarification, I understand that the only issue is with a local variable and a global variable of the same name (the static
attribute makes no difference with regards to this issue).
Inside a function, a local variable is always "preferred by the compiler" over a global variable with the same name. In other words, in function f
, all operations on variable b
are applied on the local variable and not on the global variable.