Is a static variable name, same as function name allowed in C? - c

I was working on some C-output questions and found the following code:
http://ideone.com/O0tQnr
In this code , as one can see , inside main , a static variable having same name has been declared. For this I searched on Stack-Overflow and found
How are static variables with the same name in different functions identified by the System?
The answers given for this question suggest different approaches viz.
The names of static variables are usually included within the debugging symbol table.
some embedded ones (compilers) simply add a number to the end of each duplicate name
They are likely mangled in the table.
I wanted to know how are static variables actually implemented in C, as all answers are suggesting something different?
Also to check whether this was only a one-off chance I also ran the code:
http://ideone.com/zpRVCa
but the error:
prog.c:5:21: error: called object ‘GetSize’ is not a function or function pointer
int myvar=GetSize(GetSize);
^
prog.c:4:11: note: declared here
static GetSize;
^
indicates that the compiler found a conflicting declaration / redeclared Getsize.

Different entities may have the same identifier if they have different scopes or are in different name spaces1. In the case of int main() { static int main; … }, the first main has file scope, and the second main has block scope.
At any particular point, only one identifier is visible in a name space. In GetSize(GetSize), only the static GetSize is visible. It hides the int GetSize(int), so the function GetSize is not visible. Thus, this code gets an error.
An identifier declared at file scope with static has internal linkage. An object identifier declared at block scope without extern (including those that have static) has no linkage. Because these identifiers do not have external linkage, they never need to be known outside the current translation unit. Therefore, these identifiers do not need to appear in object files: There is no need for them to have names visible to the linker. They are typically accessed by code generated by the compiler during compilation of the translation unit, and this code addresses objects numerically (by location in memory), not by name.
Many C implementations provide debugging facilities. Debuggers generally need to know the names of things even if they have internal or no linkage. In these cases, the C implementation may use any scheme it desires to record information about names.
1 The name spaces of C are: label names; tags of structures, unions and enumerations; members of structures or unions (a separate space for each structure or union); and all other identifiers. The standard also refers to a name space for macro names.

The two cases you are describing have a fundamental difference. In the first case:
int main(){
static main;
int myvar=GetSize(main);
printf("%d",myvar);
return 0;
}
Here, you are inside the function main and declaring a static integer also called main. The function main is called from an external place which knows about main as a function and calls it as such. Inside the definition of main above, you have redefined main as the static integer, then calling GetSize(main) doesn't cause an error because it complies with the definition of GetSize.
In the second case:
int GetSize(int);
int main(){
static GetSize;
int myvar=GetSize(GetSize);
printf("%d",myvar);
return 0;
}
Here you've redefined GetSize to be a static integer, but then attempted to call GetSize as if it were a function. So you have a direct conflict in terms of the definition (static integer) and how you are using it (a function).

There's a clue in the error message: "not a function or function pointer". The compiler can't assume that the name to the left of the ( is a function name, because any expression yielding a function pointer is also allowed there, including a variable declared as a function pointer.
At the parsing stage, there's no type checking to help find the right variable. Here's a program that doesn't work for a similar reason:
int main(void)
{
struct { int x,y; } s = {0,0};
{
int s;
printf("%d\n", s.x);
}
}
The outer s is capable of fitting into the expression s.x, but the inner s is the one that is visible.
And here's a program that works because the outer-scoped function is not preferred over the inner-scoped variable, which happens to be a function pointer capable of being called with itself as an argument:
#include <stdio.h>
#include <stdlib.h>
void func()
{
puts("Everything's fine.");
}
void fp()
{
/* This won't happen. */
abort();
}
int main(void)
{
void (*fp)() = func;
fp(fp);
}

Related

What is the correct interpretation of "extern" keyword in C?

In this page I cannot understand why Example 3 throws an error:
// CODE 1:
extern int var;
int main(void)
{
var = 10;
return 0;
}
There are several answers mentioning that var inside main is a local variable. But why would it not be a global variable at the same time. This code below works tough:
// CODE 2:
int var; // global
int main(void)
{
var = 10;
return 0;
}
In the case of multiple files...
... the code below works:
// CODE 3:
// File 1
extern int var;
int main(void)
{
print("%d",var);
return 0;
}
----------------
// File 2
var = 4;
... while this one does not:
// CODE 4:
// File 1
extern int var;
int main(void)
{
print("%d",var);
return 0;
}
----------------
// File 2
int func(int a) {
extern int var;
var = 3;
return 0;
}
So I could not find a meaningful explanation to the behavior of the extern keyword. How do you explain/ interpret that keyword? Also what should I change in the codes to make them work as intended?
In C, every definition is a declaration. Some declarations are definitions, and some are not.
The page you link to, has mistakes. One is it says that “Declaration of a variable or function simply declares that the variable or function exists somewhere in the program, but the memory is not allocated for them.” Actually, that is two mistakes, at least. Per C 2018 6.7 5, “A declaration specifies the interpretation and attributes of a set of identifiers…” This does not necessarily mean any object or function with the declared name actually exists in the program. For example, if we include the <stdio.h> header, the fputc function is declared, but, if we never use it, it might never be linked into the program, and so no such function might exist in the program, even in the file executable file. A declaration that is not a definition only tells the compiler about the name (which we call the identifier); it does not convey information about whether something exists.
A second mistake in that sentence is that it says memory is not allocated for the declared variable or function. This is incorrect because each definition is a declaration. C 2018 6.7 5 continues “… A definition of an identifier is a declaration for that identifier that: — for an object, causes storage to be reserved for that object; — for a function, includes the function body…” For example, int x = 3; is a declaration of x, and it is a definition of x, and it causes memory to be allocated for x, but the page you link to says a declaration does not cause memory to be allocated. So the page is wrong.
The rules regarding extern and what is or is not a definition are complicated because C was developed by multiple people doing different things with it. When C was standardized, the committee had to reconcile different practices. As a consequence, there is no single rule for extern.
A note about terminology: A variable is actually two things: an identifier (its name) and an object (the memory that stores a representation of its value).
In your CODE 1, the linked page’s Example 3, extern int var; is a declaration that is not a definition. There is no definition. If an identifier with external linkage is used in an expression, there must be exactly one external definition of it in the program (by C 2018 6.9 5). Since there is no external definition, the linker complains.
There are several answers mentioning that var inside main is a local variable.
If an identifier is declared inside a block, such as the { … } that forms the body of a function, then effects of the declaration are local to that block. If an identifier is declared outside of any function, the effects of the declaration continue through the rest of the file being compiled, except where they are hidden by a nested declaration.
If var is declared outside of any function and before main, and then we use that identifier inside main without declaring it again, that use of var refers to the previous declaration. It does not create or refer to a new local object named var.
But why would it not be a global variable at the same time.
At any one point in source code, an identifier refers to at most one thing.
.. the code below works:
…
// File 2
var = 4
var = 4 is not proper C code because it does not have a semicolon. If it were var = 4;, some compilers might accept this outside a function, but it is archaic. In modern C, it should have a type, such as int var = 4;. That would then be a proper definition of var. If your compiler accepted var = 4; outside a function, you should be aware it is accepting old code, and it would be preferable to use switches to tell the compiler to require modern C code.

How are we allowed to use a forward-declared object or function, and how are we not?

If we declare an object or function without defining it, how are we allowed to use it before its declaration and how are we not allowed to use it before its declaration ? (For a similar question using a forwarded declared structure tag before its definition, basically how we are allowed to use an incomplete type and how not, see https://stackoverflow.com/a/45725061/3284469)
Does it matter if the declaration appears in file scope or block scope?
Does it matter if its definition appears in the same or a different translation unit?
For example
extern int i;
(what can we do with i here?)
(what can't we do with i here?)
int A = i+3; // error: initializer element is not constant. This is an error not due to forward declaration of int i
int i = 3;
void fun();
(what can we do with fun here?)
(what can't we do with fun here?)
void fun(){};
Declaring an object is a promise to provide a definition at some other place. Once you declare a function or an external variable, from that point on you are allowed to do anything that you would be allowed to do to a function or a variable that you have defined.
The scope of the declaration has no effect on what you can do, only on the location in code where you can do it.
In most cases, code translator requires all external references to be satisfied at the time the code is linked. Otherwise, you get a linking error.
One exception to this rule is using declared object in a sizeof expression, which does not require an access to underlying object:
extern int undefined;
size_t res = sizeof(undefined);
The above will not break a link, because sizeof expression does not generate access to its arguments.
You can do anything with the declaration except for inlining it. For example:
void fun();
inline void fun(){}
After the declaration you can call the function, unless the definition is marked inline in which case it will result in a linker error because the definition does not emit a symbol to link against. Even if you don't say inline explicitly, an optimizing compiler may inline calls to the function if the definition has been seen.
www.cprogramming.com say's:
When you declare a variable, a function, or even a class all you are
doing is saying: there is something with this name, and it has this
type. The compiler can then handle most (but not all) uses of that
name without needing the full definition of that name. Declaring a
value--without defining it--allows you to write code that the compiler
can understand without having to put all of the details. This is
particularly useful if you are working with multiple source files, and
you need to use a function in multiple files. You don't want to put
the body of the function in multiple files, but you do need to provide
a declaration for it.
extern int i;
Here, an integer type variable i has been declared (but no definition i.e. no memory allocation for variable i so far). And we can do this declaration as many times as needed.
void fun();
Function fun() declare, but not defined. but it does tell the compiler that it can use this function and expect that it will be defined somewhere.
what can we do with i here
With
extern int i;
i can be declared as many times as required in the program.
You can have an initializer
extern int i = 0;
what can't we do with i here?
You can't use i without defining it in the program.
extern int i;
int main(void)
{
i = 10; // Will through an error
return 0;
}
In case of function this keyword only tells that the linkage for the function is extern. By default linkage of a function declaration/definition is extern.

Apparently no meaning line in a program [duplicate]

I am reading the book "Programming in C" and found in Chapter 10 an example like this:
#include <stdio.h>
void test (int  *int_pointer)
{
     *int_pointer = 100;
}
int main (void)
{
     void test (int  *int_pointer);
     int  i = 50, *p = &i;
     printf ("Before the call to test i = %i\n", i);
     test (p);
     printf ("After the call to test i = %i\n", i);
     return 0;
}
I understand the example, but I don't understand the line void test (int *int_pointer); inside of main. Why do I define the signature of test again? Is that idiomatic C?
It's definitely not idiomatic C, despite being fully valid (multiple declarations are okay, multiple definitions are not). It's unnecessary, so the code will still work perfectly without it.
If at all, perhaps the author meant to do
void test (int *int_pointer);
int main (void) {
...
}
in case the function definition was put after main ().
void test (int *int_pointer); is just a declaration (or prototype) of function test. No need of this declaration in main because you already have function definition before main.
If the definition of test were after main then it would be worth of putting its declaration there to let the compiler know about the return type, number of arguments and arguments types of test before calling it.
It's not idomatic C, but still valid.
The line is a declaration of the function test, not definition. A function can't be defined multiple times, but it's valid to have multiple declarations.
It is perfectly idiomatic C, and it actually has a (limited) practical use - although not one that is demonstrated by this example.
When you declare a function or other name at the usual global level, it is brought into scope for all function bodies in the code following the declaration. A declaration cannot be removed from a scope once it has been introduced. The function is permanently visible to the rest of the translation unit.
When you declare a function or other name within a braced block, the scope of the declaration is limited to that block. Declaring a function within the scope of another function will limit its visibility, and not pollute the global namespace or make it visible to any other functions defined in the same translation unit.
This is meaningless in the case of the example, because the definition of test also brings it into scope for all following bodies - but if test were defined in another translation unit, or even if it were defined only at the very bottom of this TU, hiding the declaration inside main would protect any other functions defined afterwards from being able to see its name in their scope.
In practical terms this is of limited use - normally if you don't want a function to be visible, you put it in another translation unit (and preferably make it static) - but you can probably contrive a situation where you might want to use this ability for constructing a module-loading system that doesn't export the original declarations of its components, or something like that (and the fact that this doesn't rely on static/separate object files might potentially have some relevance to embedded/non-hosted target environments where the linking step might not work as it does on PC, allowing you to achieve a measure of namespace protection in a purely-#include-based build system).
Example:
struct module {
void * (* alloc)(size_t);
void (* dealloc)(void *);
} loaded_module;
int main(void) {
if (USE_GC) { // dynamically choose the allocator system
void * private_malloc_gc(size_t);
void private_free_noop(void *);
loaded_module = (struct module){ private_malloc_gc, private_free_noop };
} else {
void * private_malloc(size_t);
void private_free(void *);
loaded_module = (struct module){ private_malloc, private_free };
}
do_stuff();
//...
}
// cannot accidentally bypass the module and manually use the wrong dealloc
void do_stuff(void) {
int * nums = module.alloc(sizeof(int) * 32)
//...
module.dealloc(nums);
}
#include "allocator_implementations.c"
It's not idiomatic; you typically see it in code that has problems getting their header files in order.
Any function is either used in one file only, or it is used in multiple files. If it is only used in its own file, it should be static. If it is used in multiple files, its declaration should be in a header file, and anyone using it should include the header file.
What you see here is very bad style (the function should either be static, or the declaration should be taken from a header style), and also quite pointless because the compiler can see the declaration already. Since the function is in the same file, it's not dangerous; if the declaration and function don't match the compiler will tell you. I have often seen this kind of thing when the function was in a different file; that is dangerous. If someone changes the function, the program is likely to crash or misbehave.

understanding the extern keyword in c

#include <stdio.h>
int main()
{
extern int a;
extern int a;
int a = 10;
return 0;
}
what is the problem with this code? Since multiple declaration is allowed in c what is the problem with this code
The problem with the code is that the compiler is first informed that a is a global variable (due to the extern keyword); and then a is defined as a local 'automatic' variable. Hence there is a conflict in the defined scope of a
As an alternative to automatic variables, it is possible to define variables that are external to all functions, that is, variables that can be accessed by name by any function. (This mechanism is rather like Fortran COMMON or Pascal variables declared in the outermost block.) Because external variables are globally accessible, they can be used instead of argument lists to communicate data between functions. Furthermore, because external variables remain in existence permanently, rather than appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned. —The C Programming Language
An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context. ... You should note that we are using the words definition and declaration carefully when we refer to external variables in this section. Definition refers to the place where the variable is created or assigned storage; declaration refers to places where the nature of the variable is stated but no storage is allocated. —The C Programming Language
From your question I observe that you are visualizing your program something like this
#include <stdio.h>
int main()
{
extern int a; //declaration
extern int a; //declaration
int a = 10; //declaration + definiton
return 0;
}
With above understanding of extern keyword. Your question is obvious.
Let us understand use extern of keyword thoroughly.
Extern variable declaration is a promise to the compiler that there would be a definition of a global variable some place else. Read This. In other words extern keyword tell the compiler that forget about this variable at the moment and left it to linker to link it with its definition. That is extern variables are actually linked to its definition by linker. Moreover Local variables have no linkage at all. So while searching for its definition compiler found a definition without linkage. Thats the error.
As a rule of thumb just remember when you declare any variable as extern inside any function then you can only define it outside of that function.(However there is no use of it).

What is the difference between static and extern in C?

What is the difference between static and extern in C?
From http://wiki.answers.com/Q/What_is_the_difference_between_static_and_extern:
The static storage class is used to declare an identifier that is a local variable either to a function or a file and that exists and retains its value after control passes from where it was declared. This storage class has a duration that is permanent. A variable declared of this class retains its value from one call of the function to the next. The scope is local. A variable is known only by the function it is declared within or if declared globally in a file, it is known or seen only by the functions within that file. This storage class guarantees that declaration of the variable also initializes the variable to zero or all bits off.
The extern storage class is used to declare a global variable that will be known to the functions in a file and capable of being known to all functions in a program. This storage class has a duration that is permanent. Any variable of this class retains its value until changed by another assignment. The scope is global. A variable can be known or seen by all functions within a program.
static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files.
A local variable defined in a function can also be declared as static. This causes the same behaviour as if it was defined as a global variable, but is only visible inside the function. This means you get a local variable whose storage is permanent and thus retain its value between calls to that function.
I'm no C expert so I might be wrong about this, but that's how I've understood static and extern. Hopefully someone more knowledgable will be able to provide you with a better answer.
EDIT: Corrected answer according to comment provided by JeremyP.
You can apply static to both variables and functions. There are two answers that discuss the behaviour of static and extern with respect to variables, but neither really covers functions. This is an attempt to rectify that deficiency.
TL;DR
Use static functions whenever possible.
Only declare external functions in headers.
Use the headers where the functions are defined and where the functions are used.
Don't declare functions inside other functions.
Don't exploit the GCC extension with function definitions nested inside other functions.
External functions
By default, functions in C are visible outside the translation unit (TU — basically the C source file and included headers) in which they are defined. Such functions can be called by name from any code that notifies the compiler that the function exists — usually by a declaration in a header.
For example, the header <stdio.h> makes visible declarations of functions such as printf(), fprintf(), scanf(), fscanf(), fopen(), fclose(), and so on. If a source file includes the header, it can call the functions. When the program is linked, the correct library must be specified to satisfy the function definition. Fortunately, the C compiler automatically provides the library that provides (most of) the functions in the standard C library (and it usually provides a lot more functions than just those). The 'most of' caveat applies because on many systems (Linux, for instance, but not macOS), if you use functions declared in the <math.h> header, you need to link with the maths library ('math' library if you're American), which usually is indicated by the option -lm on the linker command line.
Note that external functions should be declared in headers. Each external function should be declared in one header, but one header may declare many functions. The header should be used both in the TU where each function is defined and in each TU that uses the function. You should never need to write a declaration for a global function in a source file (as opposed to a header file) — there should be a header to declare the function and you should use that header to declare it.
Static functions
As an alternative to generally visible functions, you can make your own functions static. This means that the function cannot be called by name from outside the TU in which it is defined. It is a hidden function.
The primary advantage of static functions is hiding details which the outside world doesn't need to know about. It is a basic but powerful information hiding technique. You also know that if a function is static, you do not need to look for uses of the function outside the current TU, which can greatly simplify the search. However, if the functions are static, there can be multiple TUs which each contain a definition of a function with the same name — each TU has its own function, which may or may not do the same thing as a function with the same name in a different TU.
In my code, I qualify all functions except main() with the keyword static by default — unless there's a header that declares the function. If I subsequently need to use the function from elsewhere, it can be added to the appropriate header and the keyword static removed from its definition.
Declaring functions inside other functions
It is possible, but very inadvisable, to declare a function inside the scope of another function. Such declarations fly in the face of Agile Development maxims such as SPOT (Single Point of Truth) and DRY (Don't Repeat Yourself). They're also a maintenance liability.
However, you can, if you so desire, write code such as:
extern int processor(int x);
int processor(int x)
{
extern int subprocess(int);
int sum = 0;
for (int i = 0; i < x; i++)
sum += subprocess((x + 3) % 7);
return sum;
}
extern int subprocess(int y);
int subprocess(int y)
{
return (y * 13) % 37;
}
The declaration in processor() suffices for it to use subprocess(), but is otherwise unsatisfactory. The extern declaration before the definition is necessary if you use GCC compiler options such as:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
> -c process.c
process.c:12:5: error: no previous prototype for ‘subprocess’ [-Werror=missing-prototypes]
int subprocess(int y)
^~~~~~~~~~
cc1: all warnings being treated as errors
$
This is, I find, a good discipline, similar to what C++ enforces. It's another reason I make most functions static, and define the functions before they're used. The alternative is to declare static functions at the top of the file and then define them in whatever order seems appropriate. There are some merits to both techniques; I prefer to avoid the need to declare and define the same function in the file by defining before use.
Note that you cannot declare a static function within another function, and if you attempt to define a function such as subprocess() as a static function, the compiler gives an error:
process.c:12:16: error: static declaration of ‘subprocess’ follows non-static declaration
static int subprocess(int y)
^~~~~~~~~~
process.c:5:20: note: previous declaration of ‘subprocess’ was here
extern int subprocess(int);
^~~~~~~~~~
Since functions that are externally visible should be declared in a header, there is no need to declare them inside a function, so you should never run into this as a problem.
Again, the extern is not necessary in the function declaration inside the function; if omitted, it is assumed. This can lead to unexpected behaviour in novice programs here on SO — you sometimes find a function declaration where a call was intended.
With GCC, the option -Wnested-externs identifies nested extern declarations.
Called by name vs called by pointer
If you have a nervous disposition, stop reading now. This gets hairy!
The 'called by name' comment means that if you have a declaration such as:
extern int function(void);
you can write in your code:
int i = function();
and the compiler and linker will sort things out so that the function is called and the result used. The extern in the declaration of the function is optional but explicit. I normally use it in a header file to match the declaration of those rare global variables — where the extern is not optional but mandatory. Many people disagree with me on this; do as you wish (or must).
Now what about static functions?
Suppose the TU reveal.c defines a function static void hidden_function(int) { … }.
Then, in another TU openness.c, you cannot write :
hidden_function(i);
Only the TU that defines the hidden function can use it directly. However, if there's a function in reveal.c that returns a function pointer to the hidden_function(), then the code openness.c can call that other function (by name) to get a pointer to the hidden function.
reveal1.h
extern void (*(revealer(void)))(int);
Obviously, that's a function that takes no arguments and returns a pointer to a function that takes an int argument and returns no value. No; it isn't pretty. One of the times it makes sense to use typedef on pointers is with pointers to functions (reveal2.h):
typedef void (*HiddenFunctionType)(int);
extern HiddenFunctionType revealer(void);
There: much simpler to understand.
See Is it a good idea to typedef pointers for a general discussion on the subject of typedef and pointers; the short summary is "it isn't a good idea except perhaps with function pointers".
reveal1.c
#include <stdio.h>
#include "reveal1.h"
static void hidden_function(int x)
{
printf("%s:%s(): %d\n", __FILE__, __func__, x);
}
extern void (*(revealer(void)))(int)
{
return hidden_function;
}
Yes, it is legitimate (but very unusual) to define the function with an explicit extern — I very, very seldom do it, but here it emphasizes the role of extern and contrasts it with static. The hidden_function() can be returned by revealer(), and could be called by code inside reveal.c. You can remove the extern without changing the meaning of the program.
openness1.c
#include <stdio.h>
#include "reveal1.h"
int main(void)
{
void (*revelation)(int) = revealer();
printf("%s:%s: %d\n", __FILE__, __func__, __LINE__);
(*revelation)(37);
return 0;
}
This file cannot usefully contain a direct call by name to hidden_function() because it is hidden in the other TU. However, the revealer() function declared in reveal.h can be called by name and it returns a pointer to the hidden function, which can then be used.
reveal2.c
#include <stdio.h>
#include "reveal2.h"
static void hidden_function(int x)
{
printf("%s:%s(): %d\n", __FILE__, __func__, x);
}
extern HiddenFunctionType revealer(void)
{
return hidden_function;
}
openness2.c
#include <stdio.h>
#include "reveal2.h"
int main(void)
{
HiddenFunctionType revelation = revealer();
printf("%s:%s: %d\n", __FILE__, __func__, __LINE__);
(*revelation)(37);
return 0;
}
Sample outputs
Not the most exciting output in the world!
$ openness1
openness1.c:main: 7
reveal1.c:hidden_function(): 37
$ openness2
openness2.c:main: 7
reveal2.c:hidden_function(): 37
$
Both of these modifiers have something to do with memory allocation and linking of your code. The C standard[3] refers to them as storage-class specifiers. Using those allows you to specify when to allocate memory for your object and/or how to link it with the rest of the code. Let’s have look on what exactly is there to specify first.
Linking in C
There are three types of linkage – external, internal and none. Each declared object in your program (i.e. variable or function) has some kind of linkage – usually specified by the circumstances of the declaration. Linkage of an object says how is the object propagated through the whole program. Linkage can be modified by both keywords extern and static .
External Linkage
Objects with external linkage can be seen (and accessed) through the whole program across the modules. Anything you declare at file (or global) scope has external linkage by default. All global variables and all functions have external linkage by default.
Internal Linkage
Variables and functions with internal linkage are accessible only from one compilation unit – the one they were defined in. Objects with internal linkage are private to a single module.
None Linkage
None linkage makes the objects completely private to the scope they were defined in. As the name suggests, no linking is done. This applies to all local variables and function parameters, that are only accessible from within the function body, nowhere else.
Storage duration
Another area affected by these keywords is storage duration, i.e. the lifetime of the object through the program run time. There are two types of storage duration in C – static and automatic.
Objects with static storage duration are initialized on program startup and remain available through the whole runtime. All objects with external and internal linkage have also static storage duration. Automatic storage duration is default for objects with no linkage. These objects are allocated upon entry to the block in which they were defined and removed when the execution of the block is ended. Storage duration can be modified by the keyword static .
Static
There are two different uses of this keyword in the C language. In the first case, static modifies linkage of a variable or function. The ANSI standard states:
If the declaration of an identifier for an object or a function has
file scope and contains the storage-class specifier static , the
identifier has internal linkage.
This means if you use the static keyword on a file level (i.e. not in a function), it will change the object’s linkage to internal, making it private only for the file or more precisely, compilation unit.
/* This is file scope */
int one; /* External linkage. */
static int two; /* Internal linkage. */
/* External linkage. */
int f_one()
{
return one;
}
/* Internal linkage. */
static void f_two()
{
two = 2;
}
int main(void)
{
int three = 0; /* No linkage. */
one = 1;
f_two();
three = f_one() + two;
return 0;
}
The variable and function() will have internal linkage and won’t be visible from any other module.
The other use of static keyword in C is to specify storage duration. The keyword can be used to change automatic storage duration to static. A static variable inside a function is allocated only once (at program startup) and therefore it keeps its value between invocations
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
The output will look like this:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
Extern
The extern keyword denotes, that “this identifier is declared here, but is defined elsewhere”. In other words, you tell the compiler that some variable will be available, but its memory is allocated somewhere else. The thing is, where? Let’s have a look at the difference between declaration and definition of some object first. By declaring a variable, you say what type the variable is and what name it goes by later in your program. For instance you can do the following:
extern int i; /* Declaration. */
extern int i; /* Another declaration. */
The variable virtually doesn’t exist until you define it (i.e. allocate memory for it). The definition of a variable looks like this:
int i = 0; /* Definition. */
You can put as many declaration as you want into your program, but only one definition within one scope. Here is an example that comes from the C standard:
/* definition, external linkage */
int i1 = 1;
/* definition, internal linkage */
static int i2 = 2;
/* tentative definition, external linkage */
int i3;
/* valid tentative definition, refers to previous */
int i1;
/* valid tenative definition, refers to previous */
static int i2;
/* valid tentative definition, refers to previous */
int i3 = 3;
/* refers to previous, whose linkage is external */
extern int i1;
/* refers to previous, whose linkage is internal */
extern int i2;
/* refers to previous, whose linkage is external */
extern int i4;
int main(void) { return 0; }
This will compile without errors.
Summary
Remember that static – the storage-class specifier and static storage duration are two different things. Storage duration is a attribute of objects that in some cases can be modified by static , but the keyword has multiple uses.
Also the extern keyword and external linkage represent two different areas of interest. External linkage is an object attribute saying that it can be accessed from anywhere in the program. The keyword on the other hand denotes, that the object declared is not defined here, but someplace else.
Static
The static variables declared with the keyword static. The static variable initial value is 0. The static variables has block file scope scope.
Extern
A program in C, particularly when it is large, can be broken up into smaller programs. After compiling these, each program file can be joined together to form the large program. These small programs modules that combine together may need some variable that is used by all of them. In C, such a provision can be made by specifying these variables, accessible to all the small program modules, as an external storage class variable. These variables are global to all the small program modules that are formed as separate files. The keyword for declaring such global variables is extern.
Such a global variable is declared like any other variable in one of the program modules while the declaration of these variables is preceded with the keyword extern in all other combining program modules.
The program modules may also be a function or a block. These variables remain in existence as long as the program is in execution and their existence does not terminate upon the exit of a function or block or a program module from its state of execution. These variables are stored in the primary memory and their default value is zero.
Storage classes in C

Resources