Hi Gurus,
I got confused about a C global variable question.
There are 3 very simple C files:
mya.c
---------------------
#include <stdio.h>
int tv=10;
printav()
{
printf("&av= %x\tav = %d\n", &tv, tv);
}
------------------------
myb.c
------------------------
#include <stdio.h>
int tv= 20;
printbv()
{
printf("&bv= %x\tbv = %d\n", &tv, tv);
}
---------------------------------
mymain.c
---------------------------------
#include <stdio.h>
main()
{
printav();
printbv();
return;
}
-------------------------------------
Build program with following command:
gcc mymain.c mya.c myb.c -o myab
Then the linker complain:
ld: fatal: symbol `tv' is multiply defined:
(file mya.o and file myb.o);
if I change mya.c to :
-------------------------
#include <stdio.h>
int tv;
printav()
{
tv = 10;
printf("&av= %x\tav = %d\n", &tv, tv);
}
--------------------------
Then build myab will be successful. result is:
&av= 21784 av = 10
&bv= 21784 bv = 10
Who can help to explain this?
How does C allocate and initialize global variable?
Thanks in advance!!!
Scott
I got confused about a C global variable question.
There are 3 very simple C files:
mya.c
---------------------
#include <stdio.h>
int tv=10;
printav()
{
printf("&av= %x\tav = %d\n", &tv, tv);
}
------------------------
myb.c
------------------------
#include <stdio.h>
int tv= 20;
printbv()
{
printf("&bv= %x\tbv = %d\n", &tv, tv);
}
---------------------------------
mymain.c
---------------------------------
#include <stdio.h>
main()
{
printav();
printbv();
return;
}
-------------------------------------
Build program with following command:
gcc mymain.c mya.c myb.c -o myab
Then the linker complain:
ld: fatal: symbol `tv' is multiply defined:
(file mya.o and file myb.o);
if I change mya.c to :
-------------------------
#include <stdio.h>
int tv;
printav()
{
tv = 10;
printf("&av= %x\tav = %d\n", &tv, tv);
}
--------------------------
Then build myab will be successful. result is:
&av= 21784 av = 10
&bv= 21784 bv = 10
Who can help to explain this?
How does C allocate and initialize global variable?
Thanks in advance!!!
Scott