static (file/module level):
static, the scope is limited to the compiled module (file).extern:
Important: static is for hiding implementation, extern is for linking between modules.
Example:
main.c:
static int hidden_var = 5; extern int shared_var; int main() { printf("shared %d", shared_var); }
shared.c:
int shared_var = 10;
Attempting to use hidden_var from another file will cause a linking error.
What happens when defining a variable with the same name and different specifiers static/extern in different modules?
Answer: Each static variable (for example, static int foo; in different files) is a completely independent object. The declaration extern int foo; looks for one shared global variable named foo. Mixing static and extern is not allowed – this will lead to a linking error if in one file foo is defined as static, and in another declared extern.
Story In the project, the duplication of identically named functions (without static) was discovered in different modules: the linker linked only one of them, the other "got lost", which affected application logic.
Story In a large project, a global variable
int counter;was declared in two modules, both times without extern. As a result, the application's behavior depended on the linking order, sometimes causing conflicting symbols.
Story A module used a function with incorrect scope: it was defined as static, and the developer tried to call it from another source – the program would not compile without changing the modifier to extern (or removing static).