Saturday, May 2, 2015

C language from BaseBand Processor Eng perspective Part-9 Keywords CONST, EXTERN STATIC



The use of const in C is not much, we can use #define or enum for better result.

But if defining constant pointer , than there will be need for this.

// I WILL CHECK MY CODE, TO SEE WHERE WE ARE USING CONST, AND CAN WE HAVE USED DEFINE IN THAT CASE


Global variables are EXTERN by default. But we need EXTERN when we are using a single variable across files.

If you have defined the global variable in  .H file , and included this across C files.

When after compiling , if you link all files error will be thrown saying multiple declaration present.

So in that case in .H file we have EXTERN , then in one of files we define the variable.


Code Example

1) header.h file

#include

extern int a;

2) first.c file

#include"header.h"

int a=20;

int main()
{
printf("%d",a);
secondtype();
}

3) second.c file

#include"header.h"

void secondtype()
{
a=70;
printf("%d",a);
}


Now if you are using gcc , then

1) We use below cmd to complie files

gcc -c first.c   // this will produce objeect file  first.o
gcc -c second.c  //  second.o

2) Then we can link them to produce output file , which is windows exe equivalent

gcc -o output first.o second.o

3) to run , type below

> ./output


Now the last keyword which is used . STATIC

STATIC is mostly used

1) for defining function as static
2) local variables as static
3) limiting scope of global variable to file level


Ex Code for  1 and 3

If we are using  same function name and global variable in two different C files, then we have to use static so that their visibility is limited to that file.

1) first.c file

#include

static int a=10;

int main()
{

printf("%d",a);
secondtype();
}

2) second.c file

static int a=90;

void static secondtype()
{
printf("%d",a);
}

// This program is fine for global variable a , since in both files they are STATIC.

But since we have static  the  secondtype function , we can't use it in first.c file.

So to use  secondtype   function, we either remove static  or can define different version of secondtype  in first.c  file.


For 2nd use,  below is code .   We use it when to preserve value of a variable across function calls.


1) example.c

#include

int main()
{
  int i=0;
  for(;i<10 data-blogger-escaped-i="" data-blogger-escaped-p="">  {
   printf("number of time exam is held %d", exam());
  }
}

int exam()
{
static int a;
a++;
return a;
}



No comments:

Post a Comment