ProgrammingHardProduct company OA

Why should a header file shared by several .c files not contain the line `int counter = 0;`?

  1. A. Every .c file that includes it defines counter, causing a multiple-definition error at link time; the header should declare extern int counter; and one .c file should define it
  2. B. It works, but counter is reset to 0 each time a function is called
  3. C. Headers may not contain initialised variables of any kind
  4. D. counter would be private to the header and invisible to the .c files

Correct answer: A. Every .c file that includes it defines counter, causing a multiple-definition error at link time; the header should declare extern int counter; and one .c file should define it

#include pastes the text, so each translation unit gets its own definition with an initialiser, and the linker sees several definitions of one external name. The declaration/definition split (extern in the header, one definition in a .c file) is the standard fix.

More C Programming questions

Exams that ask this topic