ProgrammingC Developer

Explain the difference between static and extern for variables and functions in C. How does the scope affect module organization?

Pass interviews with Hintsage AI assistant

Answer

  • static (file/module level):

    • For variables and functions declared as static, the scope is limited to the compiled module (file).
    • Such a function/variable is not "visible" in other source files.
  • extern:

    • Used to declare a function/variable defined in another module. It informs the compiler: "this variable/function exists elsewhere".

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.

Trick Question

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.

Examples of real errors due to ignorance of the nuances of the topic


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).