Sunday, May 13, 2012

About extern and static

About Extern and static .


Extern is the keyword give the linkage to another file to use the same variable .

Where as static is the keyword limit the linkage to internal . If we used the function name begin with static the scope of the variable is limited to internal.


#include <stdio.h>

int bar=34;

int main()

{

barTest();

printf("\n Bar in main---%d", bar);

return 0;

}// main file name is static1.c


#include <stdio.h>

extern int bar;

void barTest()

{

printf("\n Bar in barTest---%d", bar);

}// add.c subfile


output will be

Bar in barTest---34

Bar in main---34



Now change the program little bit


#include <stdio.h>

int bar=34;// changed

int main()

{

barTest();

printf("\n Bar in main---%d", bar);

return 0;

}// main file name is static1.c


#include <stdio.h>

static int bar=90;// changed hear

void barTest()

{

printf("\n Bar in barTest---%d", bar);

}// add.c subfile


output will be

Bar in barTest---90

Bar in main---34


int bar in add.c is limited to local to that file

now without both static as well as extern

At the time of linkage the this will produce error

Now come to function using static


#include <stdio.h>

int bar=34;

int main()

{

barTest();

printf("\n Bar in main---%d", bar);

return 0;

}// main file name is static1.c


#include <stdio.h>

extern int bar;

static void barTest()

{

printf("\n Bar in barTest---%d", bar);

}// add.c subfile

Now the void barTest is implicit to the file add.c if called from other file .

it will restrict access the compiler will give the error as “undefined reference to barTest”

No comments:

Post a Comment