linker - c program involving linking get strange output -
in s1.c
:
#include <stdio.h> int foo(); struct t1 { int j; int k; int i; } a; int main() { foo(); printf("%d %d %d\n", a.i, a.j, a.k); }
in s.c
:
struct t1 { int i; int j; int k; } a; int foo() { a.i = 5; a.j = 7; a.k = 9; return 0; }
compile gcc s.c s1.c -o ee
run ./ee
, got following output: 9 5 7
.
i know has linking, what's reason in deed?
this program exhibit of undefined behavior: when declaration of struct
in 1 translation unit not match definition in other translation unit, program ill-defined, , can anything.
in case, got lucky, , program printed numbers in opposite order. although did on system, there no requirement program same (or run!) on standard-compliant system. because types of fields match pairwise (j
<==> i
, k
<===> j
, i
, <===> k
). if change types of i
, j
, , k
char
, double
, , int
, program print garbage values or crash.
from c99, 6.2.7.1:
two structure, union, or enumerated types declared in separate translation units compatible if tags , members satisfy following requirements: if 1 declared tag, other shall declared same tag. if both complete types, following additional requirements apply: there shall one-to-one correspondence between members such each pair of corresponding members declared compatible types, , such if 1 member of corresponding pair declared name, other member declared same name. 2 structures, corresponding members shall declared in same order. 2 structures or unions, corresponding bit-fields shall have same widths. 2 enumerations, corresponding members shall have same values. (emphasis added)
Comments
Post a Comment