Y
yossi.kreinin
Hi!
When are multiple definitions of global variables with the same name
considered legal in C, and how is it different from C++? It appears
that in terms of assembly language, some C definitions are translated
to "weak" symbols, in which case multiple definitions are merged by the
linker, while some become "normal" symbols, triggering linker errors in
case they are defined more then once. Is it true that in C++, multiple
definitions are always disallowed?
This code (2 translation units) compiles with gcc -ansi, but triggers
linker errors with g++:
//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];
void f();
int main()
{
printf("&a=%p\n",a);
f();
}
//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];
void f()
{
printf("f: &a=%p\n",a);
}
Compiled with gcc, it prints:
&a=0x80495e0
f: &a=0x80495e0
- showing that the definitions `int a[5]' and `int a[10]' were merged.
A symbol table listing shows that the dimension of a[] in the linked
binary is 10. Adding initializers to the definitions, for example,
triggers linker errors in C.
Thanks in advance!
Yossi
When are multiple definitions of global variables with the same name
considered legal in C, and how is it different from C++? It appears
that in terms of assembly language, some C definitions are translated
to "weak" symbols, in which case multiple definitions are merged by the
linker, while some become "normal" symbols, triggering linker errors in
case they are defined more then once. Is it true that in C++, multiple
definitions are always disallowed?
This code (2 translation units) compiles with gcc -ansi, but triggers
linker errors with g++:
//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];
void f();
int main()
{
printf("&a=%p\n",a);
f();
}
//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];
void f()
{
printf("f: &a=%p\n",a);
}
Compiled with gcc, it prints:
&a=0x80495e0
f: &a=0x80495e0
- showing that the definitions `int a[5]' and `int a[10]' were merged.
A symbol table listing shows that the dimension of a[] in the linked
binary is 10. Adding initializers to the definitions, for example,
triggers linker errors in C.
Thanks in advance!
Yossi