c - When a strong symbol and weak symbol have different data types, whose data type is chosen? -


if have 2 different c files -

main.c

void f(void); int x = 38; int y = 39;  int main() {  f();  printf("x = %d\n", x);  printf("y = %d\n", y);  return 0; } 

swap.c

double x; void f() {  x = 42.0; } 

my question since int x stronger symbol here, shouldn't "x" initialized int , when function f called, x = 42.0 store x 42. instead x becomes 0 since double being written int.

when program run, after linking both files, output

x = 0 y = 1078263808

there no difference in "strength" of 2 declarations of x in 2 files. however, fact declarations differ , x has external linkage in both files makes linking 2 single executable undefined behaviour.

the consequence, can see, program not produce sensible output.

in typical c implementation, linker not notice declaration mismatches this, , c standard not require diagnostic message emitted. still invalid program.

mandatory standard references:

§6.2.7 compatible type/paragraph 2:

all declarations refer same object or function shall have compatible type; otherwise, behavior undefined.

§5.1.1.3 diagnostics/paragraph 1:

a conforming implementation shall produce @ least 1 diagnostic message … [if a] translation unit contains violation of syntax rule or constraint … diagnostic messages need not produced in other circumstances


Comments