Sunday, September 20, 2015

C Language : Extern


I marvel at the way we humans are designed or made. We simply can't remember things which we are not in contact with for a certain period of time .

Its like either our memory gets rewritten by new memories or the way of accessing our old memories is not good enough.

I am pretty sure , I would have read about EXTERN a lot of times, but not using it on daily basis and suddenly again we have to go to some book, to check the usage.

Then the second thing is curiosity. I know a certain way of using EXTERN, but then a sudden urge will come to see what if  I have defined it in some other way or some other place and etc etc .

Now One more time and quite possibly not the last time , here again I go about EXTERN.


All the below program snippet use GCC on Ubuntu

To best see how extern works,  compile each .C file separately and  then make executable

Program 1)

extern.c file

#include<stdio.h>
int a=10;

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

extern2.c

int a=20;

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

Compile both programs
gcc -c extern.c
gcc -c extern2.c

two object files will be generated  extern.o  and extern2.o

Try to generate executable
gcc -o output extern.o extern2.o

You wll get LINKING ERROR , saying multiple defination of a

Program 2)

Now remove the int a=20;  line in extern2.c  and try again

This time you will see , COMPILE ERROR for extern2.c , since a is undefined.

Program 3)

In extern2.c , add    extern int a;  at the start

  This will work and no error will come , since

1) having extern , tells compiler to check for a at run time .
2) At run time , only one declaration of a is present in extern.c

Program 4)

What if you add  extern int a=2; either in extern.c or extern2.c

There will be no compile error, but extern will not work,  it will be simply as you have defined
int a=2;



What about local variable defined as extern ?

This will not have any effect.
1) If you initialize value at same time as declaring then COMPILE ERROR will come.

else

it will simply treat a as global variable, note that a should be declare as global variable in some file.

ex

Program 5)

extern.c

#include<stdio.h>

int main()
{

extern int a=8;          // COMPILE ERROR


Program 6)

extern.c

#include<stdio.h>

int main()
{

extern int b;
printf("%d",b);
}

extern2.c

int b=10;

int func()
{
printf("%d",b);
}

This will work.

Even

extern.c

#include<stdio.h>

int b=10;

int main()
{

extern int b;

printf("%d",b);
}

will work.

Program 7)

extern.c

#include<stdio.h>

int main()
{

extern int b;
printf("%d",b);
}

extern2.c


int func()
{
int b=10;
printf("%d",b);
}

There will be no COMPILE ERROR, but will be LINK ERROR  since there is no global definition of  a.

If you try the above programs, you will pretty much know the working of extern.




No comments:

Post a Comment