Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a variable's linkage and storage specifier?

Tags:

c++

c

When someone talks about a variables storage class specifier, what are they talking about?
They also often talk about variable linkage in the same context, what is that?

like image 934
Benoit Avatar asked Sep 18 '08 19:09

Benoit


1 Answers

The storage class specifier controls the storage and the linkage of your variables. These are two concepts that are different. C specifies the following specifiers for variables: auto, extern, register, static.

Storage
The storage duration determines how long your variable will live in ram.
There are three types of storage duration: static, automatic and dynamic.

static
If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.

automatic
If the variable is declared in a function, but without the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size).

dynamic
If you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.

Linkage
Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.

no linkage
This variable is only visible where it was declared. Typically applies to variables declared in a function.

internal linkage
This variable will be visible to all the functions within the file (called a translation unit), but other files will not know it exists.

external linkage
The variable will be visible to other translation units. These are often thought of as "global variables".

Here is a table describing the storage and linkage characteristics based on the specifiers

  Storage Class   Function            File 
  Specifier        Scope              Scope  
-----------------------------------------------------
  none           automatic         static      
                 no linkage        external linkage

 extern          static            static
                 external linkage  external linkage

 static          static            static
                 no linkage        internal linkage

  auto           automatic         invalid
                 no linkage

register         automatic         invalid
                 no linkage
like image 124
Benoit Avatar answered Oct 18 '22 08:10

Benoit