External variables in C are variables that are declared outside of any function and are accessible to multiple source files within a program. They allow sharing data between different parts of a program, such as functions in separate source files. External variables are declared using the extern keyword to indicate that their storage is defined elsewhere in the program. Here’s a detailed explanation of external variables in C:
Characteristics of External Variables:
- Declaration:
- External variables are declared outside of any function, typically at the beginning of a source file or in a header file.
- They are declared using the extern keyword to indicate that their storage is defined elsewhere.
- Scope:
- External variables have file scope, meaning they are accessible throughout the source file in which they are declared.
- They are not visible outside their source file by default unless explicitly declared as extern in other source files.
- Lifetime:
- External variables have a lifetime that extends throughout the program’s execution.
- They are allocated and deallocated once during the program’s lifetime.
- Memory Allocation:
- Memory for external variables is typically allocated in the data segment of memory.
- The memory is allocated and initialized when the program starts, and deallocated when the program terminates.
Example of External Variables:
File1.c:
#include <stdio.h>
extern int num; // Declaration of external variable
int main() {
printf(“Value of num in File1: %d\n”, num); // Accessing external variable
return 0;
}
File2.c:
int num = 10; // Definition of external variable
In this example:
- num is an external variable declared in File1.c with the extern keyword.
- The definition of num is provided in File2.c, where it is assigned the value 10.
- File1.c can access and use the value of num because it’s declared as extern.
- The linker resolves references to num by associating them with the definition in File2.c.
Use Cases of External Variables:
- Sharing Data Between Source Files:
- External variables allow sharing data between functions defined in separate source files.
- Global Configuration Settings:
- External variables can be used to store global configuration settings that are accessed by multiple parts of a program.
- Maintaining State:
- External variables can be used to maintain state information across multiple function calls within a program.
- Shared Resources:
- External variables are useful for sharing resources such as file handles, buffers, and counters across different parts of a program.
External variables provide a mechanism for sharing data between different parts of a program, facilitating modularity, code reuse, and flexibility in program design. However, their use should be judicious to avoid potential issues related to data integrity and encapsulation.