Shadowing of static global and local identifiers

后端 未结 1 1280
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 08:36

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

相关标签:
1条回答
  • 2021-01-16 09:06

    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:

    • If you declare it in a header file, then use extern as prefix, and include the header file in every source file that makes use of this variable.
    • If you declare it in a source file, then you will have to declare it as 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:

    • A local variable
    • A static local variable
    • A static global variable
    • A non-external global variable

    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.

    0 讨论(0)
提交回复
热议问题