ProgrammingHardProduct company OA
Why should a header file shared by several .c files not contain the line `int counter = 0;`?
- 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
- B. It works, but counter is reset to 0 each time a function is called
- C. Headers may not contain initialised variables of any kind
- 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
- With 4-byte int, what is printed? c int n = 0; int f(void) { n++; return 1; } int main(void) { sizet s = sizeof(f()); printf("%zu %d", s…
- What is printed? c int n = 3, s = 0; while (n--) s += n; printf("%d %d", s, n);
- Assume ASCII. What is printed? c int cmp(const void a, const void b) { return strcmp((const char )a, (const char )b); } int main(void) {…
- What is printed? c int g[3][3] = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}; int mp(int r, int c) { if (r == 0 && c == 0) return g[0][0]; if (r < 0…
- What is printed? c unsigned next(unsigned x) { unsigned c = x & -x, r = x + c; return (((r ^ x) >> 2) / c) | r; } int main(void) {…
- What is printed? c const char s = "abcabcab"; const char p = strstr(s, "cab"); printf("%td %s %td", p - s, p + 3, strstr(p + 1, "cab") - s);