Storage duration and linkage
suggest changeStorage duration describes how long an object exists. Scope describes where an identifier is visible, and linkage determines whether declarations in different scopes or translation units refer to the same entity. These concepts are related but are not interchangeable.
Storage-class specifiers
staticgives a block-scope object static storage duration. At file scope, it gives an object or function internal linkage.externdeclares an identifier that usually has external linkage and refers to a definition elsewhere.thread_localgives an object thread storage duration. At block scope, combine it withstaticorextern. C11 through C17 spell it_Thread_local.registercan be used for an automatic object and prevents taking that object's address. Modern optimizers choose register allocation without this hint, so new code rarely uses it.typedefdeclares a type alias. It is syntactically categorized as a storage-class specifier even though it does not give an object storage duration.autohistorically made automatic storage duration explicit at block scope. C23 also permits it to request type inference from an initializer.
Only one storage-class specifier normally appears in a declaration; thread_local may be combined with static or extern.
static unsigned process_count; /* Static duration, internal linkage. */
extern const char *program_name; /* Defined in another translation unit. */
thread_local unsigned request_count; /* One object per thread. */
unsigned example(void)
{
int local = 0; /* Automatic storage duration. */
static int call_count; /* Static storage duration. */
auto inferred = 42; /* C23: inferred as int. */
++call_count;
return process_count + request_count + call_count + local + inferred;
}
Storage durations
Automatic objects normally exist from entry into their block until execution leaves it. A pointer to such an object becomes invalid when the object's lifetime ends. Implementations commonly use a stack or registers for these objects, but the C standard does not require either representation.
Static objects exist for the entire execution of the program. File-scope objects have static storage duration whether or not their declarations contain static.
Thread-local objects exist for the lifetime of a thread, with a distinct instance for each thread that refers to them.
Dynamically allocated objects have allocated storage duration. Their lifetime begins when an allocation function succeeds and ends when the storage is deallocated.
Linkage
An identifier can have external linkage, internal linkage, or no linkage. A file-scope function or object normally has external linkage. Adding static gives it internal linkage, so it is visible by name only within that translation unit. Most block-scope identifiers have no linkage; a block-scope extern declaration refers to an entity with linkage.