Thursday, April 30, 2015

C language from BaseBand Processor Eng perspective Part-7 Externs

It's so much difficult to debug code when it spans across multiple files.

In case of baseband , it can be 1k files.  And to figure out the error you have to build baseband binary , check in real time emulating scenario and keeps on fixing.

Therefore sometimes it is good to have concept clear.  One other C keyword used extensively is EXTERN.

You will almost see this being defined in almost every C file of baseband processor code.


1) Extern on variables.

int main(){

extern int a;
a=10;
printf("%d",a);

}

int main(){

extern int a=10;
a=20;
printf("%d",a);

}

Run the above two codes , debug more on your own with extern inside function and you will know

>>  Using EXTERN inside function is useless. It doesn't serves any purpose.

Further  , when we define       extern int a;     // it doesn't allocates memory to a;
when we define                       extern int a=10;   // memory is allocated,  but compilation error will be thrown, but same will work if defining it for global variable.


Now defining it for global variable,

extern int a;

int main(){

a=10;
printf("%d",a);

}

extern int a=10;

int main(){

a=10;
printf("%d",a);

}

What we see is that if we DECLARE variable using EXTERN  no memory is allocated, but variable is declared.
so no COMPILATION ERROR,  but LINKER error is thrown.

Why LINK ERROR , since at compilation time due to extern COMPILATION thinks this varibale will be DEFINED some where else and mark it as unresolved symbol.  At Linkage time, compiler is not able to find any DEFINATION and hence it will give "symbol unresolved" error.

Just try to check if below code throws any error

extern int a;
int a=10;
int main(){

a=20;
printf("%d",a);
}

and also this one  and  notice the error thrown if any

extern int a=2;
int a=3;
int main(){

a=5;
}

Here error saying "redefination of int a" will come, which is compile time error.
Also to remove that error if we remove int a=3 will work.

But best practice will be to not have value initialized to variable if we are using EXTERN.




No comments:

Post a Comment