0
0
Cprogramming~5 mins

Extern storage class

Choose your learning style9 modes available
Introduction

The extern storage class tells the compiler that a variable or function is defined in another file or place. It helps share variables or functions across multiple files.

When you want to use a variable defined in another file.
When you want to share a global variable between different source files.
When you want to declare a function that is defined elsewhere.
When you want to avoid multiple definitions of the same variable.
When organizing large programs into multiple files.
Syntax
C
extern data_type variable_name;
extern return_type function_name(parameter_list);

The extern keyword only declares the variable or function; it does not allocate memory.

The actual variable or function must be defined exactly once elsewhere without extern.

Examples
This declares that an integer variable named count exists somewhere else.
C
extern int count;
This declares a function display defined in another file.
C
extern void display();
This declares an external character array named message.
C
extern char message[];
Sample Program

This example shows two parts: one file defines the variable number, and the other file declares it with extern to use it. When linked together, the program prints the value of number.

C
// File 1: define.c
int number = 10; // definition of variable

// File 2: use.c
#include <stdio.h>
extern int number; // declaration of external variable

int main() {
    printf("Number is %d\n", number);
    return 0;
}
OutputSuccess
Important Notes

Without extern, declaring the same variable in multiple files causes errors.

extern helps the linker find the actual variable or function during program build.

Use extern only for declarations, not definitions.

Summary

extern declares variables or functions defined elsewhere.

It allows sharing data across multiple files.

Helps avoid duplicate definitions and linker errors.