Storage duration and linkage

suggest change

Storage 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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents