Sunday, April 21, 2013

Global vs global static variable in C?

Global has external linkage (all declarations in other files refer to it).
Global and static has internal linkage (local to the file).

Example: (From Book: Expert C Deep C Secrets)

function apple (){ /* visible everywhere */ }
extern function pear () { /* visible everywhere */ }
static function turnip(){ /* not visible outside this file */ } 

---

To the view the draft for free http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

The following is from the C Standard (Draft 2011):

6.2.2 Linkages of identifiers (first 5 points): 
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.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.

2) There is no linkage between different identifiers.

4 - For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5 - If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.


No comments:

Post a Comment