In C, the static and extern keywords define the scope (visibility) and lifetime of variables or functions. Different usage patterns have distinct effects on program behavior.
static keyword
The static keyword serves two primary purposes:
-
Limiting scope: When
staticis applied to a variable within a function, it extends the variable's lifetime to span the entire program execution while keeping its scope confined to the function where it is defined. Such variables are termed static local variables. The value of a static local variable persists across function calls, rather than being reinitialized.Example:
cvoid function() { static int count = 0; // Initialized on first call and retains value in subsequent calls count++; printf("This function has been called %d times\n", count); }Here, each invocation of
functionretains and incrementscount's value. -
Limiting linkage: When
staticis used for a global variable or function, it modifies the linkage property, making them visible only within the file where they are defined and inaccessible to other files. This helps avoid name collisions and ensures data encapsulation and hiding.Example:
cstatic int value = 5; // Cannot be accessed from other files static void secretFunction() { printf("This is an internal function, not visible externally\n"); }Both
valueandsecretFunctionare inaccessible outside their defining source file.
extern keyword
The extern keyword declares a global variable or function whose definition resides in another file. It informs the compiler that the symbol is defined elsewhere, enabling sharing of global variables or functions across multiple files in a multi-file project.
-
Referencing symbols in other files:
externsignals to the compiler that a symbol is defined in another file.Example:
c// Defined in file1.c int globalVar = 100; // Declared and used in file2.c extern int globalVar; void useGlobalVar() { printf("globalVar = %d\n", globalVar); }In this case,
globalVaris defined infile1.cand declared/used infile2.c.
Summary
- Using
staticrestricts the scope of variables or functions and maintains the persistence of local variables. - Using
externenables sharing of variables or functions across multiple files, enhancing code modularity and reusability.
These keywords are critical for managing data and function access permissions in large-scale software projects.