Umesh said:
How Globals are handle in C since global variables can be acessed by
any function in that program.
Is it they stored in heap so they can be acessed across fuction.OR how
they handle in c.
It seems you are asking how they are accessed rather than how they are
stored. The C langage doesn't mention 'global' in any context. I assume
you mean a variable in one file which can be accessed by statements and
functions in another file. If not, please ignore the rest of this.
Assume I have a program consisting to two .c translation units and a
single .h header, foo.c, bar.c and foo.h.
The header will look like this..
extern int x;
...simply declaring that there is an int called x out there somewhere.
There is bar.c which looks like..
#include "foo.h"
void bar(void) {
x = 2;
}
The main TU, foo.c, looks like this..
#include <stdio.h>
#include "foo.h"
int x = 1;
int main(void) {
printf("%d\n", x);
bar()
printf("%d\n", x);
return 0;
}
In foo.c the variable 'int x' is declared and defined outside any
function and therefore has 'external' linkage. This means the linker
will be able to 'see' its name and address at link time. foo.h provides
the declaration of x as 'int x' but does not provide an address.
Including foo.h in foo.c is not useful in this case, but harmless. There
may be other declarations in foo.h that foo.c needs.
I use gcc so I'll demonstrate that. Compile the two .c TU's to object
files..
gcc -c foo.c
...creates foo.o and..
gcc -c bar.c
...creates bar.o. Then..
gcc foo.o bar.o -o foo.exe
...will create the executable. Because x has external linkage, foo.o will
provide the linker with its address. Then as bar.o is looking for x, the
linker will assign its address in bar.o such that the assignment in
bar() is treating the variable defined in foo.c.
I didn't know this would take so long.