ProgrammingHardWipro · Cognizant pattern

What happens when these two files are linked together?

What happens when these two files are linked together?
/* file1.c */
extern int shared;
void show(void) { printf("%d", shared); }

/* file2.c */
int shared = 99;
int main(void) {
    show();
}
  1. A. Prints 99
  2. B. Linker error: shared is declared but never defined
  3. C. Prints 0
  4. D. Compile-time error: extern requires an initializer

Correct answer: A. Prints 99

file1.c's extern int shared; is just a DECLARATION, promising the linker that shared is defined somewhere (with external linkage). file2.c provides that actual definition, int shared = 99;. The linker successfully resolves file1.c's reference to file2.c's definition, so show() correctly reads and prints 99.

More C Programming questions

Exams that ask this topic