Thursday, September 24, 2009

extern and static

extern:
1. declaration to access external variables


case one
...
extern int i; //if declared at external scope, can be accesed by any function onwards in this file
...
foo(){
int j = i; //access to external variable i;
...
}


case two

foo(){
extern int i; //if declared inside an function, can only be accessed in this file
int j = i;
}

Note: any variable NOT defined inside a function is by default external unless it is explicitly declared to be static

2. declaration to access external functions
Any function in C/C++ is by default external unless it is explicitly declared to be static
int foo() {} //external, accessible by functions in other files
static int foo() {} //static, only accessible in this file

int foo() ; = external int foo() ;
Compiler figures out when seeing ";" that "int foo(); " is a declaration, NOT a definition. Compiler defaults such declaration to external

static
static variables

case one
...
static int i; //if declared at external scope, qualify i, defined at this spot, so that i can only be accessed in this file
...
foo(){
int j = i; //access to static external variable i;
...
}

case two

foo(){
static int i; //if declared inside an function, make i survive from one "foo()" call to another
int j = i;
}

static function
static int foo() {} //only accessible in this file