C linkage example: In the program shown, where is variable 'a' declared and where is it defined? (extern int a; ... int a = 20;)

Difficulty: Easy

Correct Answer: extern int a is declaration, int a = 20 is the definition

Explanation:


Introduction / Context:
The C language distinguishes between declaration (introducing a name and type) and definition (allocating storage or providing a body). This is especially important for global variables, which are often declared in headers and defined in exactly one source file. The snippet uses 'extern int a;' and later 'int a = 20;'. We must identify which line declares and which line defines the object 'a'.


Given Data / Assumptions:

  • Global context contains 'extern int a;' inside main's scope (visible as a declaration) and later a global definition 'int a = 20;'.
  • We are discussing a non-const, non-static integer with external linkage.
  • Standard C rules for declarations/definitions apply.


Concept / Approach:

  • 'extern int a;' is a declaration only: it promises that a definition exists elsewhere and does not allocate storage.
  • 'int a = 20;' is a definition: it allocates storage and initializes the variable with 20.
  • One program must have exactly one definition for 'a' with external linkage; multiple declarations are allowed.


Step-by-Step Solution:

Classify the 'extern' line → declaration without storage.Classify the 'int a = 20;' line → definition (creates the object and initializes it).Therefore, declaration is 'extern int a;' and definition is 'int a = 20;'.


Verification / Alternative check:

If you remove 'int a = 20;' and link, you will get an unresolved external symbol for 'a'; adding the definition resolves the reference.


Why Other Options Are Wrong:

  • Swapping declaration/definition reverses roles and is incorrect.
  • Claiming 'a is not defined' contradicts the explicit definition present.
  • Stating both are declarations ignores that initialization with storage constitutes a definition.


Common Pitfalls:

  • Placing a definition in a header and including it in multiple files causes multiple-definition linker errors.
  • Confusing 'extern' on variables (suppresses definition) with 'extern' on functions (redundant for linkage).


Final Answer:

extern int a is declaration, int a = 20 is the definition

Discussion & Comments

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