Try Embedded

Scope, linkage and storage duration

What static really means, declarations versus definitions, and where each variable lives.

Three separate questions about every name

For every variable and function, C answers three independent questions. Confusing them is behind most "multiple definition" errors, most mysterious globals, and a favourite interview question about static.

QuestionTermPossible answers
Where in the source can the name be used?ScopeBlock (inside {}), file, function prototype
Can other files refer to the same object?LinkageExternal, internal, none
How long does the object exist?Storage durationAutomatic, static, allocated, thread

Storage duration

DurationCreatedDestroyedInitial valueLives in (typical MCU)
Automatic (locals)On entry to the blockOn exit from the blockIndeterminate (garbage)Stack or registers
Static (globals, static locals)Before mainNeverZero, or the initialiser.data or .bss in RAM; const ones often in flash
AllocatedmallocfreeIndeterminate (calloc: zero)Heap

A static local keeps its value between calls, because its storage duration is static even though its scope is the block:

#include <stdio.h>

static unsigned next_sequence(void) {
  static unsigned counter;      // zero before main, keeps its value between calls
  return ++counter;
}

int main(void) {
  for (int i = 0; i < 3; i++) printf("sequence %u\n", next_sequence());
  return 0;
}

This is how a driver keeps state privately without a global: the counter cannot be touched by any other function.

Linkage

DeclaredLinkageVisible to
At file scope, no staticExternalEvery file that declares it
At file scope with staticInternalOnly this file (translation unit)
Inside a block (without extern)NoneOnly this block

So static means two different things depending on where it is written:

  • At file scope it changes linkage: the name is private to the file.
  • Inside a function it changes storage duration: the variable outlives the call.
/* uart.c */
static uint8_t rx_buffer[256];      // internal linkage: no other file can see it
static void handle_byte(uint8_t b); // private helper
void uart_init(void) { ... }        // external linkage: part of the module's interface

Making everything that is not part of a module's interface static is the single most useful habit for keeping a firmware codebase maintainable: it shrinks the global namespace, lets the compiler optimise (and warn about unused functions), and documents the interface.

Declarations, definitions and extern

  • A definition creates the object (allocates storage) or provides the function body. Each object or function with external linkage must be defined exactly once in the whole program.
  • A declaration only announces a name and its type. It may appear many times.
  • extern makes a file-scope variable declaration not a definition.
/* config.h: declarations, included everywhere */
extern uint32_t g_baud_rate;
void config_load(void);

/* config.c: the one definition */
uint32_t g_baud_rate = 115200;
void config_load(void) { ... }

The classic mistakes

MistakeSymptom
uint32_t g_baud_rate; (no extern) in a header included by two filesmultiple definition of 'g_baud_rate' (since GCC 10, which defaults to -fno-common; older compilers silently merged them)
A variable defined static in a headerEvery file gets its own private copy; changes in one file are invisible in another
Declaration and definition with different typesUndefined behaviour the linker cannot detect; include the header in the defining file so the compiler checks it
A function used without a prototypeImplicit declaration (an error in C99 and later with proper warnings): wrong argument types silently passed

Tentative definitions

At file scope, int x; without an initialiser and without extern is a tentative definition: within one file it can appear several times, and becomes a definition initialised to zero. Older toolchains also merged tentative definitions across files ("common" symbols), which hid duplicate globals. Modern GCC and Clang no longer do, so write extern in headers and define once.

Where things end up in memory

int counter;                    // .bss (zeroed by startup code)
int baud = 115200;              // .data (initial value copied from flash at startup)
static const uint16_t sine[256] = { ... };   // .rodata in flash: no RAM used
void f(void) {
  int local;                    // stack (or a register)
  static int calls;             // .bss: static duration, block scope
  char *msg = "hello";          // pointer on the stack; the characters in .rodata (flash)
}

The linker map shows each one; see the lessons on startup code and ELF and map files.

Interview question: Explain the different meanings of the keyword static in C.

Answer: At file scope, static gives a variable or function internal linkage: it is private to that translation unit. Inside a block, static gives a variable static storage duration: it is initialised once, before main, and keeps its value between calls while remaining visible only in that block. (In C99 it also appears in array parameter declarations, int a[static 4], promising at least four elements.) In C++ it additionally marks class members shared by all instances.

Interview question: What is the difference between a declaration and a definition?

Answer: A declaration introduces a name and its type so the compiler can check its use; a definition also creates it, allocating storage for a variable or supplying the body of a function. A program may contain many declarations of a name but exactly one definition of each object or function with external linkage. In practice headers hold extern declarations and prototypes, and exactly one .c file holds each definition, including its own header so the compiler checks they agree.

Going deeper

Interview question: How would you keep a motor-control library's internals private when three products use it?

Answer: Expose only a small header with the functions and types the products need; make everything else static in the .c files, so other modules cannot link to it. Put the module's state in a struct the library owns (an opaque handle) rather than globals, and version the interface so changes are deliberate.

Interview question: Where do initialised and uninitialised globals live, and what makes them hold their values before main?

Answer: Uninitialised (and zero-initialised) globals and static locals go in .bss, which the startup code fills with zeros. Globals with non-zero initialisers go in .data: their initial values are stored in flash and copied to RAM by the startup code before main. const globals usually go in .rodata in flash and need no copying. Locals live on the stack and are not initialised at all.

Interview question: Why is it a good idea to make every non-interface function in a module static?

Answer: Internal linkage hides the function from other files, so the module's real interface is exactly what its header declares. It prevents accidental name clashes and dependencies on internals, lets the compiler warn about unused functions, and enables more optimisation such as inlining a helper called once and removing the out-of-line copy. It is the C equivalent of private members.

Explain it: In your own words, explain scope, linkage and storage duration, using a static variable inside a function as the example.

Answer: Scope is where in the source code a name can be used; linkage is whether other files can refer to the same object; storage duration is how long the object exists. A static variable inside a function has block scope, so only that function can name it, no linkage, so no other file can reach it, and static storage duration, so it is created and zeroed (or initialised) before main and keeps its value between calls. That combination makes it useful for private state such as a counter or an initialised-once flag.