Thursday, September 24, 2015

C language : Static and Extern



Some of points regarding static and extern.

1) By default , global variables are extern

2) Local variables are neither extern or static by default.

3) Defining a local variables as extern, doesn't have any effect.
3.1) defining local variables as extern and assigning value to it results in COMPILE ERROR.

So never have local variables as extern.

4) Local variables as static saves its value between function calls.

Also it is better to have value assigned to static value at time of definition.

5) Define global variable as STATIC only if you want that variable scope as limited to that file.


Both STATIC and EXTERN variable are saved either in BSS if uninitialized and in DATA if initialized.



Regarding to function, compiler treat them as implicitly EXTERN. therefore we don't need to add extern in front of function.

But if you need to limit the scope of function to some one file, then static can be added in front of function.

But then LINK ERROR will come if you are trying to access this function from some other file.

STATIC with function name is mostly used if you have 2 definition of same function, then you can limit the scope of one function by using STATIC.

No comments:

Post a Comment