Answer in brief
extern is commonly used to declare an object or function whose definition is supplied elsewhere, possibly in another source file.
Declaration and definition
extern int total; /* declaration */
int total = 10; /* definition at file scope */
Working
The declaration tells the compiler the name and type. The definition supplies the object. When compatible declarations have external linkage, they can refer to the same object across translation units. A header can contain an extern declaration while one source file contains the definition.
Example explanation
In the complete single-file example, total is declared before main and defined after main. The earlier declaration makes the name available when main is compiled. The definition gives total the initial value 10, which main prints. The order is chosen to show the difference clearly.
Important rules
- Keep the declared type compatible with the definition.
- Provide one required external definition rather than putting an ordinary initialised definition in every included header.
- Do not assume extern makes a previously hidden name visible automatically: a declaration must appear in an appropriate scope.
- An extern declaration with an initialiser at file scope is a definition, so the initialiser changes the situation.
Linkage and storage duration
An object declared with external linkage has static storage duration. However, extern is not simply another word for global: a block-scope extern declaration can refer to an object defined outside that block. Linkage also depends on prior visible declarations, so avoid the oversimplification that extern always overrides an earlier static declaration.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
extern int total;
int main(void)
{
printf("Total = %d\n", total);
return 0;
}
int total = 10;
Sample input and output
This example uses values already written in the program.
Output
Total = 10
Related exam questions
Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
- September/October 2021 · Q1(b) · 8 marks
If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.
Paper P01 · page 1 - July 2021 · Q2(c) · 5 marks
List and explain storage classes in C.
Paper P04 · page 1
View this category in the exam question bank →