ProgrammingHardWipro · Cognizant pattern

What happens at link time?

What happens at link time?
// file1.c
static int counter = 0;
void increment(void) { counter++; }
// file2.c (compiled and linked with file1.c)
extern int counter;
int main(void) {
    printf("%d", counter);
}
  1. A. Linker error: counter has internal linkage in file1.c (due to static) and is not visible to file2.c's extern declaration
  2. B. It links fine and prints a garbage value
  3. C. Compilation error: static variables cannot be named counter
  4. D. It links fine and prints 0

Correct answer: A. Linker error: counter has internal linkage in file1.c (due to static) and is not visible to file2.c's extern declaration

`static` at file scope gives counter INTERNAL linkage, confining it to file1.c's translation unit only; file2.c's `extern int counter;` looks for an externally-linked symbol named counter, which doesn't exist (file1's is hidden), causing an unresolved external symbol at link time.

More C Programming questions

Exams that ask this topic