ProgrammingHardProduct-company MCQ pattern

Two files are compiled and linked together. What happens?

Two files are compiled and linked together. What happens?
/* file1.c */
static int counter = 0;
void inc(void) { counter++; }

/* file2.c */
extern int counter;
int main(void) {
    inc();
    printf("%d", counter);
}
  1. A. Prints 1
  2. B. Prints 0
  3. C. Compile-time error in file2.c: counter has internal linkage in file1.c, so extern int counter cannot see it there
  4. D. Linker error: multiple definitions of counter

Correct answer: C. Compile-time error in file2.c: counter has internal linkage in file1.c, so extern int counter cannot see it there

static at file scope gives counter INTERNAL linkage, confining it to file1.c alone; no other translation unit can refer to it, no matter how it declares extern. file2.c's extern int counter; refers to a DIFFERENT (non-existent, in this case) external symbol, so linking fails with an unresolved external reference, which a well-behaved toolchain reports essentially as this kind of link-time error.

More C Programming questions

Exams that ask this topic