ProgrammingHardHCL · Tech Mahindra pattern

file1.c:

file1.c:
static int secret = 7;
int getSecret(void) { return secret; }
file2.c:
int getSecret(void);
int main(void) { printf("%d", getSecret()); }
What happens when these are linked?
  1. A. Linker error, same as accessing secret directly would be
  2. B. Prints 7 — functions default to external linkage, so getSecret is visible across files even though secret itself is hidden
  3. C. Compile error: getSecret must also be declared static
  4. D. Prints 0, secret's internal linkage blocks the accessor too

Correct answer: B. Prints 7 — functions default to external linkage, so getSecret is visible across files even though secret itself is hidden

static only hides the data object secret from other translation units. getSecret is declared without static, so it has the usual default external linkage and is perfectly visible to file2.c, which can call it to read the hidden value indirectly — exactly the encapsulation pattern static globals are used for.

More C Programming questions

Exams that ask this topic