C linkage and scope: if a global (external) variable is defined earlier in the same source file, must a function still declare it with extern before using it?

Difficulty: Easy

Correct Answer: Applies (the statement is correct)

Explanation:


Introduction / Context:
This question probes understanding of C linkage and declaration requirements. Global variables have file scope and external linkage by default (unless declared static). If a definition appears before a use, the identifier is already known to subsequent code in that translation unit.



Given Data / Assumptions:

  • A single source file (translation unit) is considered.
  • The global variable has been defined (not just declared) before the function that uses it.
  • The variable is not declared static.


Concept / Approach:
In C, a definition of an external object at file scope also serves as a declaration that introduces the name and its type to the rest of the translation unit that follows. Therefore, no additional extern declaration inside a function is required to use it. The extern keyword is needed when referencing an object that is defined elsewhere (e.g., another file) or before its definition is visible.



Step-by-Step Solution:
Place the definition at file scope before functions: int g = 42;Later function uses g directly without redeclaring extern g; → valid.If g were defined in another file, then extern int g; would be needed in this file to declare it.



Verification / Alternative check:
Compilers accept use of a previously defined external variable without an additional extern. Moving the definition below the function and omitting a prior declaration will cause a diagnostic in modern C.



Why Other Options Are Wrong:
Does not apply: contradicts the rule that a prior definition suffices.Static: static changes linkage to internal; extern is irrelevant in that case.Order dependency: only matters if the definition comes after; our case has it before.Compiler-dependent: this is defined by the C standard, not implementation whim.



Common Pitfalls:
Confusing declarations with definitions; forgetting that extern inside a function does not define storage; assuming extern is always required.



Final Answer:
Applies (the statement is correct)

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion