Topics / C Programming / Q2
What does the static keyword do in different contexts?
Short answer: static has two different meanings. Inside a function, it makes a local variable keep its value between calls (static storage duration, initialised once). At file scope, on a global variable or a function, it gives internal linkage: the name is visible only inside that .c file, which is how C makes things "private".
static int counter; /* file-private global: other .c files cannot see it */
static void helper(void) { } /* file-private function */
int next_id(void)
{
static int id = 100; /* initialised once, before main(); keeps its value */
return id++; /* 100, 101, 102, ... */
}
Details
- A static local is initialised only once, and only with a constant expression in C (C++ allows run-time initialisation on first call).
- Its lifetime is the whole program, but its scope is still the function body.
- File-scope
staticprevents name clashes: two files can each have astatic int count;without a "multiple definition" link error.
Embedded uses
- Driver state that only the driver may touch:
static uint8_t rx_buf[64]; static volatile uint16_t rx_head;inuart.c, with public functions as the only interface. This is C's equivalent of encapsulation. - Keeping state in callbacks or state machines between calls.
Pitfalls
- A static local makes a function non-reentrant: two tasks or an ISR calling it at the same time share the variable.
staticin a header file gives every.cfile that includes it its own private copy, which wastes memory and is rarely what you want (except forstatic inlinefunctions, which is the normal idiom).- (C99)
staticinside array parameter brackets,void f(int a[static 4]), means "the caller passes at least 4 elements"; a third, rarely used meaning.