Global variable and static global variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shadyabhi
    New Member
    • Dec 2008
    • 18

    Global variable and static global variable

    I heard that all global variables are static..

    If its so then what is the difference between the 2 declarations:
    Code:
    #include<stdio.h>
    
    int a;
    static int b;
    
    main()
    {
    ....
    }
    What is the difference between there visibility and how long they remain in memory?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    They are both in memory for the entire lifetime of the program. The variable that is declared static only has scope in the file in which it is declared where as the variable declared without static can be accessed from other files using an extern declaration.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      The meaning of the "static" keyword in C depends on whether or not it appears within a brace-delimited block. Refer to the following code snippet.
      Code:
      int a;
      static int b;
      
      int func(void) {
         int c;
         static int d;
         ...
      }
      Variables 'a' and 'b' are declared outside of any brace-delimited blocks, therefore they both persist for the life of the program and are accessible from anywhere in the compilation unit. In this case, the "static" keyword has the effect of making variable 'b' local to the compilation unit. Variable 'a' can be accessed from any other compilation units that contain an extern declaration for it.

      Variables 'c' and 'd' are declared within a brace-delimited block, therefore they are only accessible from within that block. In this case, the "static" keyword has the effect of making variable 'd' persist for the life of the program. Variable 'c' only persists while execution is within that brace-delimited block. There is no reason to expect variable 'c' to be stored at the same location for successive executions of the brace-delimited block.

      I would expect C++ to be consist with C in this regard, but I don't know that for a fact.
      Last edited by Banfa; Jan 7 '09, 04:28 PM. Reason: Corrected static int c; to static int d;

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        It is the same in C++

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          One last note. Neither variable 'c' nor 'd' are accessible from other compilation units. Any attempt to add an extern declaration for either of them to another compilation unit will result in a link error.

          (Banfa: thanks for fixing my typo!)

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            C++ is consistent with C as faras the static keyword is concerned. However, in C++ the static keyword is largely deprecated and is in the language generally for backwards compatibility with C. There remain some uses of it, however.

            No one has mentioned linkage so far, which is odd. Linkage comes in two flavors, external and internal. External linkage means the variable or function is accessible (sharable) from outside the compilation unit. Internal linkage means the variable/function is accessible onlt from inside the compilation unit.

            So a static function cannot be called from outside the compilation unit but an external one can:
            Code:
            extern void MyFunction(int arg)
            {
                /* etc... */
            }
            The function prototype is:
            Code:
            extern void MyFunction(int arg);
            The extern is the default. External functions (aka global functions) are callable by using the function prototype.

            Static functions cannot be called from outside the compilation unit:
            Code:
            static void MyFunction(int arg)
            {
                /* etc... */
            }
            The function prototype is:
            Code:
            static void MyFunction(int arg);
            You may place the static function prototype at the top of the file but the definition of the function must reside somewhere in the file.

            The above applies to variables.
            Code:
            extern int value;
            This variable is accessible from another compilation unit by:
            Code:
            extern int value;
            Static variables have internal linkage and are accessible only in the current scope. If the static variable is inside a function, it is accesssible only from inside the function. Here the static keyword also causes the local variable to persist after the function completes execution. It's kind of like a local global.

            Comment

            • shadyabhi
              New Member
              • Dec 2008
              • 18

              #7
              ok i understood it. thanks for your support.

              Comment

              • vamskk
                New Member
                • Jun 2009
                • 3

                #8
                Global static

                Global static variables are accessable from other files. The static is to make the variable retain the last assigned value. But what is given below says global static variables are not accesable from other file.

                ex.






                Originally posted by donbock
                The meaning of the "static" keyword in C depends on whether or not it appears within a brace-delimited block. Refer to the following code snippet.
                Code:
                int a;
                static int b;
                
                int func(void) {
                   int c;
                   static int d;
                   ...
                }
                Variables 'a' and 'b' are declared outside of any brace-delimited blocks, therefore they both persist for the life of the program and are accessible from anywhere in the compilation unit. In this case, the "static" keyword has the effect of making variable 'b' local to the compilation unit. Variable 'a' can be accessed from any other compilation units that contain an extern declaration for it.

                Variables 'c' and 'd' are declared within a brace-delimited block, therefore they are only accessible from within that block. In this case, the "static" keyword has the effect of making variable 'd' persist for the life of the program. Variable 'c' only persists while execution is within that brace-delimited block. There is no reason to expect variable 'c' to be stored at the same location for successive executions of the brace-delimited block.

                I would expect C++ to be consist with C in this regard, but I don't know that for a fact.

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by vamskk
                  Global static variables are accessable from other files. The static is to make the variable retain the last assigned value. But what is given below says global static variables are not accesable from other file.

                  ex.
                  http://knol.google.com/k/vivek-bhadr...4lj4klzp0d/36#
                  Nowhere in this (old) thread it is written that global static variables would be accessible from other translation units. Global static variables don't have external linkage. Of course their address can be passed around at will.

                  btw, in that blog function main is written as 'void main()', that is a strong indication to me that the blogger doesn't know much about C or C++. Don't take that blog as the truth.

                  kind regards,

                  Jos

                  Comment

                  • vamskk
                    New Member
                    • Jun 2009
                    • 3

                    #10
                    Static global variable in header

                    The link that is given discusses about can static global variables be defined in .h file and the answer is yes. So that should not matter if it is defined in a .c file and would be accesable from another file in the same project using extern.

                    May be the information given is not authentic. Thank you JOASH.

                    Could you give some authentic links for global static variables and its definition.

                    Thanks and Regards,
                    Vamskk

                    Comment

                    • donbock
                      Recognized Expert Top Contributor
                      • Mar 2008
                      • 2427

                      #11
                      Originally posted by vamskk
                      Global static variables are accessable from other files. The static is to make the variable retain the last assigned value. But what is given below says global static variables are not accesable from other file.
                      http://knol.google.com/k/vivek-bhadr...4lj4klzp0d/36#
                      I recommend you avoid the phrase global static variable. This is a Cheshire Cat term: it means what you want it to mean -- a condition ripe for confusion. Using the language of the Standard may be pedantic, but it is precise and unambiguous.

                      Originally posted by C99 Standard, section 6.2.2 (Linkages of identifiers)

                      An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. There are three kinds of linkage: external, internal, and none.

                      In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

                      If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.

                      For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

                      If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

                      The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.

                      If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.
                      Originally posted by C99 Standard, section 6.2.4 (Storage duration of objects)

                      An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated. Allocated storage is described in 7.20.3 [Memory management functions: calloc, free, malloc, realloc].

                      The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

                      An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

                      An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration.

                      For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

                      For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration. If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.
                      Notice that linkage applies to identifiers while storage duration applies to objects.

                      All the confusion arises because the same keyword, static, indicates both linkage and storage duration.

                      I suppose you intended the phrase global static variable to mean an object with static storage duration whose identifier has internal linkage.

                      This exposition is consistent with the explanations already provided for this [old] thread. The difference is that I've been deliberately pedantic.

                      Comment

                      • Tassos Souris
                        New Member
                        • Aug 2008
                        • 152

                        #12
                        Originally posted by vamskk
                        The link that is given discusses about can static global variables be defined in .h file and the answer is yes. So that should not matter if it is defined in a .c file and would be accesable from another file in the same project using extern.

                        May be the information given is not authentic. Thank you JOASH.

                        Could you give some authentic links for global static variables and its definition.

                        Thanks and Regards,
                        Vamskk
                        Let's say that we have a file defs.h that has a "static global" variable like you call it.
                        In file main.c you include defs.h so what actually happens is that the variable is defined within the main.c file and that brings us to the case discussed in this topic.
                        Nothing strange.

                        Comment

                        • vamskk
                          New Member
                          • Jun 2009
                          • 3

                          #13
                          In a proj all .c files concerning to that project are compiled together. Is it not as good as they are like include files? So global static variable from other .c file can be accessed by extern command. Is it not so?

                          Comment

                          • donbock
                            Recognized Expert Top Contributor
                            • Mar 2008
                            • 2427

                            #14
                            Originally posted by vamskk
                            In a proj all .c files concerning to that project are compiled together. Is it not as good as they are like include files?
                            No. Each .c file is compiled separately into its own .o file; then all of the .o files are linked together.

                            It is possible for one .c file to #include all of the other .c files -- the preprocessor doesn't know any better. However nobody does that. It would look very odd.

                            Originally posted by vamskk
                            So global static variable from other .c file can be accessed by extern command. Is it not so?
                            Since each .c file is compiled separate, then each is considered a separate compilation unit. Only external linkage can bridge compilation units; and then only if both compilation units declare the variable with extern.

                            PS. I have this sneaking suspicion that "compilatio n unit" is not the pedantic term. Don't have my copy of the Standard handy to check. Hopefully you know what I mean.

                            Comment

                            • vivekbhadra
                              New Member
                              • Jun 2009
                              • 5

                              #15
                              Originally posted by JosAH
                              Nowhere in this (old) thread it is written that global static variables would be accessible from other translation units. Global static variables don't have external linkage. Of course their address can be passed around at will.

                              btw, in that blog function main is written as 'void main()', that is a strong indication to me that the blogger doesn't know much about C or C++. Don't take that blog as the truth.

                              kind regards,

                              Jos
                              =============== =============== =============== ============

                              a static variable defined in the global space in a file cannot be accessed from other files because it doesn't have an external linkage. the example I have given exactly says that. look below for once again:

                              /*Illegal use of static variable*/
                              /*File: test1.c*/
                              #include<stdio. h>
                              #include "header.h"
                              int i = 100;
                              int main() {
                              printf("This is the scope of the global variable:%d\n", i);
                              foo();
                              foo();
                              printf("This is not a scope of static variable:%d\n", j);
                              return 0;
                              }
                              /*File: test2.c*/
                              extern int i;
                              static int j = 200;
                              int foo() {
                              printf("This is the scope of the global variable: %d\n",i);
                              j++;
                              printf("in func foo() the scope of static j is: %d\n",j);
                              return 0;
                              }
                              /*File: header.h*/
                              extern int foo();
                              extern int j;

                              Error:

                              /tmp/cckXvIiw.o(.tex t+0x2f): In function `main':
                              : undefined reference to `j'

                              the above example exactly clears up your confusion. the variable 'j' has been declared as static in file 'test2.c' and 'test1.c' tries to access it as extern which the gcc compiler complain as : "undefined reference to `j' ".

                              now if you declare it( 'j' ) in a header file as static then what happens is:
                              "whenever that header file in included in a '.c' file a new memory is allocated for that variable for that particular file. Which essentially means that different files will use their respective copies of the file during the program execution. So the real significance of the static storage class vanishes when it's declared in a header file. "

                              for further information please refer


                              =============== =============== =============== ============
                              >>"in that blog function main is written as 'void main()', that is a strong indication to me that the blogger doesn't know much about C or C++"

                              Take no offense, I really donno the big deal with 'void main()' and 'int main()' and how does it really confirm a person's C/C++ knowledge ? anyways, thanks for passing the information. at least now I can judge a person's C/C++ capabilities in a moment :-)

                              cheers
                              -Vivek

                              Comment

                              Working...