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);
}- A. Prints 1
- B. Prints 0
- C. Compile-time error in file2.c: counter has internal linkage in file1.c, so extern int counter cannot see it there
- 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
- What is printed? c int x = 10; void f(void) { int x = 20; { int x = 30; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c void f(void) { register int i; int p = &i; p = 5; printf("%d", i); }
- What is printed? c int x = 100; void f(void) { extern int x; printf("%d", x); } int main(void) { f(); }
- What is printed? c void f(void) { printf("%d ", x); } int x = 42; int main(void) { f(); }
- What is printed? c int x = 5; void modify(void) { x = 10; } int main(void) { int x = 20; modify(); printf("%d %d", x, ::x == 5); }
- What is printed? c static int helper(int x) { return x 2; } int main(void) { printf("%d", helper(5)); }