Global variable and static global variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #16
    Originally posted by vivekbhadra
    So the real significance of the static storage class vanishes when it's declared in a header file. "
    That is so wrong; a C compiler doesn't know anything about header files; that's a task for the preprocessor; the compiler just works with translation units; one at the time. If you define a static variable in a header file it'll end up in every translation unit that includes that file and therefore multiple static variables will exist.

    kind regards,

    Jos

    Comment

    • vivekbhadra
      New Member
      • Jun 2009
      • 5

      #17
      Originally posted by JosAH
      That is so wrong; a C compiler doesn't know anything about header files; that's a task for the preprocessor; the compiler just works with translation units; one at the time. If you define a static variable in a header file it'll end up in every translation unit that includes that file and therefore multiple static variables will exist.

      kind regards,

      Jos
      =============== =============== =============== ==============
      and you don't want multiple copies of your static variable... right ? why does one in the first place declare a variable as a static variable in a header file ? one can only do that assuming this would be unique across the compilation units and so ( by mistake of course). but otherwise there can be no sesible reason on wants to declare something as static in a header file. that's what I have written in the blog. I have never said the compiler would complain about it but have said this would create multiple copies of the same static variable in different files. so ultimately the meaning of static doesn't hold good. let me know if there is still any confusion about it.

      Please read it once again:
      What happens when a static variable is declared in a header file?
      Of course we can declare a static variable in a header file, include that header file in .c files and access the variable from the .c files. But important thing to remember here is the fact that if a static variable is declared in a header file, then 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.
      Look at the following example(pleas elet me know which line in the following snippet is actually bothering you):

      test.h
      static int var;
      test.c
      #include<stdio. h>
      #include "test.h"
      extern int foo();
      void main(void)
      {
      printf("var in %s: %d\n ", __FILE__, ++var);
      foo();
      }
      helper.c
      #include "test.h"
      void foo(void)
      {
      printf("var in %s: %d\n",__FILE__, ++var);
      }

      Compilation:

      gcc -o statictest test.c helper.c

      Run:

      ./statictest
      Output:
      ~/test $ ./statictest
      var in test.c: 1
      var in helper.c: 1


      Now lets see the sysmbol table of "statictest " particularly focussing on how "var" variable to understand how compiler generates code for "var".
      00000000 l df *ABS* 00000000 test.c
      080496c8 l O .bss 00000004 var
      00000000 l df *ABS* 00000000 helper.c
      080496cc l O .bss 00000004 var

      However if we change the declaration in the test.h file and make the var a global variable then the whole thing changes as below:

      test.h
      int var;
      Compilation:
      gcc -o globaltest test.c helper.c
      Run:
      ./statictest
      Output:
      ~/test $ ./statictest
      var in test.c: 1
      var in helper.c: 2


      Symbol table of "globaltest " only contains a single entry for 'var':
      080496c8 g O .bss 00000004 var

      =============== =============== =============== ==========
      What I can guess is in the line "So the real significance of the static storage class vanishes when it's declared in a header file." the word significance is probably bothering you. I have written significance more from a programming perspective not from a compiler. The variable still will retain it's value because it either from the Data Section or from the BSS but for a programmer, if he is thinking this would be unique across the program is incorrect. About the multiple copies of it I have clearly mention in the line "Which essentially means that different files will use their respective copies of the file during the program execution.".

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #18
        [QUOTE=vivekbhad ra;3496072]Look at the following example(pleas elet me know which line in the following snippet is actually bothering you):

        Code:
                void main(void)
        There's no need to explain the semantics of the word 'static' to me; I know what it is. Defining (not "declaring" ) a static variable in an header file is just plain stupid and nothing of its meaning "vanishes".

        kind regards,

        Jos

        Comment

        • vivekbhadra
          New Member
          • Jun 2009
          • 5

          #19
          [QUOTE=JosAH;349 6086]
          Originally posted by vivekbhadra
          Look at the following example(pleas elet me know which line in the following snippet is actually bothering you):

          Code:
                  void main(void)
          There's no need to explain the semantics of the word 'static' to me; I know what it is. Defining (not "declaring" ) a static variable in an header file is just plain stupid and nothing of its meaning "vanishes".

          kind regards,

          Jos
          =============== =============== =============== ========
          >>There's no need to explain the semantics of the word 'static' to me; I know what it is.

          so as I do ..... and just one more information when you are talking about a header file it's always declaration not definition .... until the header file is included in a C/C++ file it never gets it's memory allocated ... so it's a declaration in a header file not definition ...

          anyway somehow I realize this conversation is going a little strange ... lets stop it .... your knowledge is not a sufficient proof of other people's ignorance .... good luck and goodbye

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #20
            [QUOTE=vivekbhad ra;3496087]
            Originally posted by JosAH
            and just one more information when you are talking about a header file it's always declaration not definition .... until the header file is included in a C/C++ file it never gets it's memory allocated ... so it's a declaration in a header file not definition ...
            When you do:

            Code:
            static int foo;
            anywhere (not just in a header file) it's a definition and it's tentative. You have managed to obfuscate an old thread that was crystal clear before. Please don't do that but get your facts straight before you post.

            kind regards,

            Jos

            Comment

            • vivekbhadra
              New Member
              • Jun 2009
              • 5

              #21
              [QUOTE=JosAH;349 6091]
              Originally posted by vivekbhadra

              When you do:

              Code:
              static int foo;
              anywhere (not just in a header file) it's a definition and it's tentative. You have managed to obfuscate an old thread that was crystal clear before. Please don't do that but get your facts straight before you post.

              kind regards,

              Jos
              =============== =============== =============== =========
              >>anywhere (not just in a header file) it's a definition and it's tentative.

              nothing is tentative in the C paradigm unless you have created your own . there is absolutely no confusion about the fact that unless a header file is included in a C file a declaration never gets into a definition as it doesn't still have a memory allocated. your repeated shout doesn't really get the variable a memory and hence it still remains a declaration. and when this header file is included in a file this variable is declared as well as defined at the same place. so there is nothing wrong in saying declaring a static variable in a header file. the matter of fact is that I have all my facts straight but probably you gotta little bit straighten your professional manners. there has been no obfuscation by my thread whatsoever. please read the link below to understand a declaration, a definition and a declaration as well as a definition.


              cheers
              vivek

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #22
                Straight from the C Standard:

                Originally posted by C Standard
                3.7.2 External object definitions

                Semantics

                If the declaration of an identifier for an object has file scope
                and an initializer, the declaration is an external definition for the
                identifier.

                A declaration of an identifier for an object that has file scope
                without an initializer, and without a storage-class specifier or with
                the storage-class specifier static , constitutes a tentative
                definition. If a translation unit contains one or more tentative
                definitions for an identifier, and the translation unit contains no
                external definition for that identifier, then the behavior is exactly
                as if the translation unit contains a file scope declaration of that
                identifier, with the composite type as of the end of the translation
                unit, with an initializer equal to 0.

                If the declaration of an identifier for an object is a tentative
                definition and has internal linkage, the declared type shall not be an
                incomplete type.

                Examples

                int i1 = 1; /* definition, external linkage */
                static int i2 = 2; /* definition, internal linkage */
                extern int i3 = 3; /* definition, external linkage */
                int i4; /* tentative definition, external linkage */
                static int i5; /* tentative definition, internal linkage */

                int i1; /* valid tentative definition, refers to previous */
                int i2; /* $3.1.2.2 renders undefined, linkage disagreement */
                int i3; /* valid tentative definition, refers to previous */
                int i4; /* valid tentative definition, refers to previous */
                int i5; /* $3.1.2.2 renders undefined, linkage disagreement */



                extern int i1; /* refers to previous, whose linkage is external */
                extern int i2; /* refers to previous, whose linkage is internal */
                extern int i3; /* refers to previous, whose linkage is external */
                extern int i4; /* refers to previous, whose linkage is external */
                extern int i5; /* refers to previous, whose linkage is internal */
                kind regards,

                Jos

                Comment

                • vivekbhadra
                  New Member
                  • Jun 2009
                  • 5

                  #23
                  Originally posted by JosAH
                  Straight from the C Standard:



                  kind regards,

                  Jos
                  =============== =============== =============== ==========
                  >>If a translation unit contains one or more tentative
                  definitions for an identifier, and the translation unit contains no
                  external definition for that identifier, then the behavior is exactly
                  as if the translation unit contains a file scope declaration of that
                  identifier

                  .... the above line from your post explains my point. a "tentative definition" without an external definition is nothing but "declaratio n" in generic terms. so there shudn't any problem saying declaring a static variable in a header file .

                  Comment

                  • donbock
                    Recognized Expert Top Contributor
                    • Mar 2008
                    • 2427

                    #24
                    My impression is that vivekbhadra and JosAH are using very different terminology; but that they both intend to describe the same practical behavior. I'm going to try to clarify ...

                    There is nothing magical about header files. The compiler sees absolutely no difference between these two cases:
                    Code:
                    header.h:
                        static int a;
                     
                    file1.c:
                        #include "header.h"
                        ...
                    
                    file2.c:
                        #include "header.h"
                        ...
                    and
                    Code:
                    file1.c:
                        static int a;
                        ...
                    
                    file2.c:
                        static int a;
                        ...
                    The result is the two files each have their own local variable. What one file does with its variable 'a' has no effect on the other file's variable 'a'. I wouldn't call this "multiple copies of the same static variable in different files" because that suggests more of a connection between the variables than actually exists. The only same-ness is that local variables in two different source files happen to have the same identifier. This happens all the time without confusing anybody; accomplishing the same thing with a header file ought not to suddenly confuse us.

                    By the way, defining a static variable in a header file is not always a mistake. I have occassionally found it useful to do so. For example, a file-scope context variable accessed by each invocation of a macro (also defined in that same header). I categorize this practice as "tricky code" and comment accordingly.


                    and just one more information when you are talking about a header file it's always declaration not definition .... until the header file is included in a C/C++ file it never gets it's memory allocated ... so it's a declaration in a header file not definition
                    That is a very fine semantic distinction. The next step would be to suggest that a text file doesn't really contain C code until it is processed by a compiler. There is some merit in this existential argument, but little utility. The ability of an experienced programmer to read and interpret a block of C code is not affected by whether or not that code is ever presented to the compiler. By the way, many C compilers have command line switches that can be set to compile a .h file as if it were a .c, so to repeat myself: there is nothing magical about header files.


                    So the real significance of the static storage class vanishes when it's declared in a header file
                    I don't understand what this statement is intended to mean. Variables declared static in a header are emphatically still static when the .c file including that header is compiled -- see the code snippets at the top of this message. Perhaps the poster meant that defining static variables in a header file won't accomplish what you're trying to do. I guess that depends on what you're trying to do.

                    Comment

                    • souma
                      New Member
                      • Jul 2014
                      • 1

                      #25
                      file means?other section of same prgrm or diff prgrm?

                      Comment

                      • donbock
                        Recognized Expert Top Contributor
                        • Mar 2008
                        • 2427

                        #26
                        @souma, are you referring to my reply #24? I was doing something a little tricky: each code snippet indicates the contents of separate text files: header.h, file1.c, and file2.c.

                        file1.c and file2.c are separate source files so each is presented separately to the C compiler. Implied in the thread is that the resulting object files are linked together into a single executable file. Presumably you intend "program" to be the same thing as "executable file".

                        Comment

                        Working...