Difference between static and extern keyword

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dipsg
    New Member
    • Jul 2007
    • 1

    Difference between static and extern keyword

    Pls tell me Difference between static and extern keyword
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Originally posted by dipsg
    Pls tell me Difference between static and extern keyword
    This extern keyword is used to specify that the variable is declared in a different file. This is mostly used to declare variables of global scope.

    The static keyword allows a variable to maintain its value among different function calls.

    Search google to have broader view :))

    Regards

    Comment

    • kky2k
      New Member
      • May 2007
      • 34

      #3
      Originally posted by dipsg
      Pls tell me Difference between static and extern keyword
      try this....

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        static and extern are called storage class specifiers.

        extern says the variable, or function, is defined ouside this source file.

        static says the variable, or function, defined in this file can be used only in this file.

        A variable or function declared static is said to have internal linkage. Whereas, a variable or function declared extern is said to have external linkage.

        There are defaults. Global variables are extern by default. Functions are extern by default. constants are static by default. These defaults can be changed. That is, you can have a static global variable or an extern constant.

        If you use the extern explicitly with a global variable you need to assign a value where the variable is defined and no value where the variable is declared.

        [code=c]
        const int data = 10; //has internal linkage
        extern const int data = 10; //has external linkage
        extern const int data; //const int data defined outside this file
        extern int data; //data defined outside this file
        extern int data = 10; //data defined here with a value of 10 and
        //external linkage
        int data = 10; //same as extern int data = 10;
        static int data = 10; //has internal linkage
        [/code]

        Comment

        • Shokry

          #5
          first of all, thanks to "weaknessforcat s" for his/her informative answer... just a couple of corrections:

          - global variables are NOT extern by default, you still need to "extern" the global in the source files where you wish to access it
          - If you use the extern explicitly with a global variable, you do NOT have to assign a value where the variable is declared

          Comment

          Working...