Storage classes in C (Auto, Register, Static, Extern)
Storage classes in C, There are four different storage classes
1. auto:
This is the default storage class for all local variables.
int a;
auto int b;
the above are both variables in the same storage class.
example.c
2. register:
The register storage class is used to define local variables that should be stored in a register instead of RAM. The variable size equal to the register size and can’t have the unary ‘&’ operator.
To see the difference between local variable and register variable we have to generate assembly level instructions.
gcc -S example.c -o example.s
For the above code offset address of x is -8(%rbp) and y is -4(%rbp). rbp – register base pointer (start of the stack)
Now modify the example.c source file to use register storage class and generate assembly level instructions.
For the above assembly code, x and y variables allocate in CPU registers.
3. static:
The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. If you use static storage class in functions so that function scope is a file scope. we can use the same function name in different files.
output:
4. extern:
The extern storage class uses to give a reference of a global variable that is visible to all program files. if you extern, “this variable declare here but is define elsewhere”.
Let’s see the above-relocated files global.o and extern.o. As global.c contains the definitions of “x” objects we can see their information as part of the Symbol Table. In global.c “fun” is declared but not defined.
As extern.c contains the definitions of the “fun” function we can see their information as part of Symbol Tabe. In extern.c x declared but not define.
Recent Comments