extern Storage Class in C
'extern' storage class
In C, the
extern
storage class is used to declare variables or functions that are defined in another file and are accessible to multiple files.The
extern
keyword tells the compiler that the variable or function is defined elsewhere and should not allocate storage for it.Here's the syntax for declaring an extern variable:
extern data_type variable_name;
- Here's the syntax for declaring an extern function:
extern return_type function_name (parameters);
Example 1
Here's an example of using the extern storage class in C:
File main.c:
#include <stdio.h>
extern int x;
int main() {
x = 10;
printf("In main: x = %d\n", x);
return 0;
}
File support.c:
#include <stdio.h>
int x;
void modify() {
x = 20;
}
Explanation
The variable x
is declared as extern in main.c and defined in support.c. The main.c file is able to access the value of x because of the extern declaration.
When the program is compiled and executed, the output will be:
In main: x = 10
This demonstrates how the extern
storage class can be used to make a variable defined in one file accessible to other files in a program.