Answer SL28


x before foo: 8
x in fileB: 444
x in fileB: 25
x after  foo: 8

/* --- fileA.c --- */
int x = 8;                   /* file scope, external linkage */

 
/* --- fileB.c --- */
#include <stdio.h>

static int x = 444 ;         /* file scope, internal linkage */

void foo()
{
  printf("x in fileB: %d\n", x );
  x = 25;
  printf("x in fileB: %d\n", x );
}

 
/* --- fileC.c --- */
#include <stdio.h>
void foo();

extern int x ;               /* file scope, external linkage */
void main()
{
  printf("x before foo: %d\n", x );
  foo();
  printf("x after  foo: %d\n", x );
}

Comments: The x in fileB.c has internal linkage, and so becomes "fileB's private x". fileB.c does not see the x of the other two files. Without the keyword static in the declaration in fileB.c, the linker would have attempted to create a single entity for the x of all three files, which would fail because of the conflicting initializations.



Back to Puzzle Home