What is the purpose of the extern keyword in C language?
In C language, the “extern” keyword is used to declare that a variable or function is defined in another file, indicating that the definition of that variable or function is in another file and the current file is just referencing it. The purpose of the “extern” keyword is to instruct the compiler to look for the definition of that variable or function in another file during the linking phase.
In C language, the declaration and definition of variables and functions are separated. Declaration informs the compiler about the existence of a variable or function, while definition allocates memory space for the variable or implements the functionality of the function. When a variable or function is used in multiple files, it needs to be declared in each file and defined in one of them. Using the extern keyword can avoid redefining variables or functions in each file.
For example, declaring a variable or function in a file:
extern int x; // Declare a variable x of type int
extern void func(); // Declare a function func with no return value
Next, define the variable or function in another file:
int x; // Define variable x
void func() { // Define the function func’s functionality }
When declaring a variable or function using the ‘extern’ keyword, the compiler will search for the definition of that variable or function in other files during the linking phase, ensuring that all references to that variable or function in different files point to the same definition. This allows for sharing variables or functions between multiple files.