-3

Firmware and compiler point of view, Why static variables can't be linked externally like globals.

rama
  • 17
  • 1
  • 5
    Globals are static in a sense they are allocated once and live for the whole time the program is executing. the `static` qualifier on a global is explicitly setting it to internal linkage. It is like asking why locked doors can't be opened. – Eugene Sh. May 18 '18 at 18:19
  • `static` applied to a variable makes it local to a file. Relevant: https://stackoverflow.com/questions/1856599/when-to-use-static-keyword-before-global-variables – J_S May 18 '18 at 18:27

1 Answers1

2

The static keyword serves double duty here. It specifies that the object has static storage duration - that is, storage for the object is allocated when the program starts and released when the program exits.

It also specifies that the identifier for that object has internal linkage. IOW, the identifier is not exported to the linker (it is effectively "private" to that translation unit).

Chapter and verse:

      6.2.2 Linkages of identifiers

1     An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. 29) There are three kinds of linkage: external, internal, and none.

2     In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.

3     If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.30)
29) There is no linkage between different identifiers.
30) A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.

If you want an object to have static storage duration, but also have its identifier visible to other translation units, then you must declare it at file scope without the static keyword:

#include <stdio.h>

int i_am_static_and_visible;
static int i_am_static_but_not_visible;

void foo( void )
{
  static int i_am_static_but_not_visible_either;
  ...
}
Community
  • 1
  • 1
John Bode
  • 119,563
  • 19
  • 122
  • 198