Thread: extern variables

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    50

    extern variables

    The foll code
    Code:
    static int a;
    extern int a;
    gave no error on gcc

    But the foll gave error :
    Code:
    static int a;
    int a;
    But I think in case of global variables 'int' and 'extern' int are same or not??

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    extern is a declaration that does not define the variable (does not actually allocate the variable). it is used when you want to refer to a variable from another file. so you can declare 'extern int a;' in the same file as the definition of int a; such as if an include file has 'extern int a;' to declare it for other files. but the second example tries to define the variable twice, which is not allowed.
    but the catch in your first example is using 'static' on the definition of 'a'. so what you are actually saying is 'i have a local static variable named 'a', and I also have a declaration of an extern variable 'a' from some other file'. thats an interesting idea. which 'a' is used locally?
    Code:
    // a.c
    #include <stdio.h>
    extern int a;
    static int a = 1;
    int main( void )
    {
    	printf("%d\n",a);
        return 0;
    }
    
    // b.c
    int a = 2;
    in Visual Studio 2012, it prints '1'. so the local static value hides the global extern.

    then another catch: if instead of 'extern int a;', you say 'extern int a = 0', you get a definition instead of just a declaration. so you would get a redefinition error if you said
    Code:
    static  int a;
    extern int a = 0;
    i don't have the standard handy. can someone point out the clause(s) in the standard?

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    This is pretty much the same question as static variables with just a slightly different context.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. extern variables
    By karnavor in forum C++ Programming
    Replies: 8
    Last Post: 03-29-2010, 08:10 AM
  2. Extern variables in GAS?
    By Kernel Sanders in forum C Programming
    Replies: 6
    Last Post: 10-20-2008, 10:10 PM
  3. redefining variables without extern
    By robwhit in forum C Programming
    Replies: 16
    Last Post: 05-23-2008, 02:24 PM
  4. allocation for global variables in extern
    By Bobert in forum C Programming
    Replies: 13
    Last Post: 12-15-2007, 07:26 PM
  5. problem with extern variables
    By crash88 in forum C Programming
    Replies: 11
    Last Post: 05-05-2006, 01:44 PM

Tags for this Thread