When I write the following program:
file 1:
#include <stdio.h>
int global;
void print_global1() {
printf("%p\n", &global);
}
file 2:
#include <stdio.h>
char global;
void print_global2() {
printf("%p\n", &global);
}
file 3:
void print_global1();
void print_global2();
int main()
{
print_global1();
print_global2();
return 0;
}
output:
$ ./a.out
0x804a01c
0x804a01c
Here is my question:
- Why are the linker implementing “int global” and “char global” as the same global variable:
- How come the compiler does not complain (not the smallest warning with
-Wall -Wextra -ansi…) - How are the size of the global variable managed (the size of int and char are different)
PS: The second question is architecture/compiler related, so lets take the gcc or Visual C++ (for C) with the int size as 32 bits
EDIT: THIS IS NOT A QUESTION FOR C++ BUT for C!
I use gcc version 4.4.1 and on Ubuntu 9.10, Here is the compilation console output:
$ ls
global_data1.c global_data2.c global_data.c
$ gcc -Wall -Wextra -ansi global_data*.c
$ ./a.out
0x804a01c
0x804a01c
or
$ gcc -Wall -Wextra -ansi -c global_data*.c
$ gcc -Wall -Wextra -ansi global_data*.o
$ ./a.out
0x804a01c
0x804a01c
gccdoes not report any error/warnings. Butg++does.EDIT:
Looks like C allows tentative definitions for a variable.
In your case both the global definitions are tentative and in that case the first one seen by the linker is chosen.
Change your file2 to:
Now if you compile like before, the tentative def in file1 will be ignored.
Make both the def explicit by:
now neither can be ignored and we get the multiple def error.