C data segment identification - c

If I declare
static int a ;// globally and
static int a ; // locally in one function
So now there are two instances of a ..
I know all static variables goes into data segment but how they are differentiated in data segment which one is local and which one is global ??

You can in fact go further: you can declare
static int a;
at file scope in two or more separate files contributing to your program. Each such declaration in a different scope declares a separate variable. Thus, given
f.c:
static int a;
int f() {
static int a;
return 0;
}
main.c
static int a;
int f(void);
int main() {
return f();
}
There are three separate static variables associated with the name a in different places. It is the compiler and linker's job to arrange for the correct storage to be associated with each variable reference.

Related

why volatile can repeat declare?

#include <stdio.h>
volatile int isInit_STD;
volatile int isInit_STD;
int main() {
printf("v-%d-addr%x\n",isInit_STD,&isInit_STD);
isInit_STD = 1;
printf("v-%d-addr%x\n",isInit_STD,&isInit_STD);
return 0;
}
and the result is:
v-0-addr387fd040
v-1-addr387fd040
why volatile can repeat declare?
It turns out they are all the same, the same address.
If one of them deletes the 'volatile', that can't be compiled success.
I want to know the reason, looking forward to your reply.
The C standard says that (C17 6.7/4)
All declarations in the same scope that refer to the same object or function shall specify compatible types.
That means that as long as you use the same name, same type and same type qualifiers (volatile etc), you can declare the variable as many times as you like, and it will all refer to the same object.
And the opposite: if you use different types or qualifiers, but give the variable the same name, it is a constraint violation and the compiler must issue a diagnostic message.
Apart from what standard C allows, common sense states that we should avoid having multiple declarations of the same variable when possible. Good program design practices also state that we should avoid declaring objects at file scope, or if that's not possible, avoid using external linkage ("globals") and instead enforce interal linkage by declaring the variable static.
I want to know the reason
You can repeat a declaration of anything as many times as you want, as long as the declarations are "the same". It's not specific to volatile, just there has to be no conflict. All declarations refer to the same thing.
The following is an actual whole .c file:
// 3 declarations of function main.
int main();
int main();
int main();
// 3 declarations of struct A type.
struct A;
struct A;
struct A;
// 3 declarations of variable a
extern volatile int a;
extern volatile int a;
extern volatile int a;
// 3 declarations of variable b
int b;
int b;
int b;
// 3 declarations of variable c
volatile int c;
volatile int c;
volatile int c;
// example with conflicts:
int d;
// volatile int d; // error - conflict with above, d is not volatile
// static int d; // error - conflict with above, d is not static
extern int d; // Fine! Stuff declared at file scope is implicitly extern.

How to globaly initialize variable in c and what is the difference between static and extern?

please explain me about how a variable scope can be globally initialized in C and what is the difference between static and extern
The scope of variable means: Where can it be seen (aka where does it exist) and thereby be accessed.
The scope of a variable depends on where in the code it is defined.
A variable gets global scope when it is defined outside a function. The keyword static can limit the scope of a global variable so that it can only be seen in that particular c-file (aka compilation unit). So:
file1.c
int gInt1; // Global variable that can be seen by all c-files
static int gInt2; // Global variable that can be seen only by this c-file
void foo(void)
{
int lInt; // Local variable
...
}
In order to use a global variable from another c-file, you tell the compiler that it exists in some other file. For this you use the extern keyword.
file2.c
extern int gInt1; // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
You often put the extern declaration into a header file. Like:
file1.h
extern int gInt1; // Any c-file that includes file1.h can use gInt1
file2.c
#include "file1.h" // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
Regarding initialization
Initializing a global variable is no different from initializing a local variable.
The only difference between global and local variables is when you do not have an initializer. In such cases a local variable will be left uninitialized while global variables will be default initialized (which typically means initialized to zero).
file1.c
int gInt1 = 42; // Global variable explicit initialized to 42
int gInt2; // Global variable default initialized to 0
void foo(void)
{
int lInt1 = 42; // Local variable explicit initialized to 42
int lInt2; // Local variable uninitialized. Value is ??
...
}
To Declare a variable of global scope ,just declare it outside all functions.
Intial value -0.
Scope of Global variable: It can be used in all functions and files.
Life- Till Program execution.
Use of extern keyword:
If you declared a global variable in a file and want to use it in another file then extern keyword is used.
int x=5; //source file
extrern int x=10; //any other file
Another use of extern keyword is if the golbal variable is used before declaration in program.
example:
void main()
{
int x
extern int y;
x=y;
}
int y=5;
Static varialbe:
intial value-0
scope- Till control remain in block,function or file.
Life -Till Program execution.
void main()
{
fun();
fun();
fun();
}
void fun()
{
int x=0;
x++;
}
After Program ends x=3.
Static Variable can also be used as global variable and declared outside all functions
but the scope remain in the file in which it is defined.
example:
static int x=2;
int main()
{
x=5;
}
That's all!

Understanding how extern works

The way I understand extern is that we are able to declare a variable anywhere in a program and use it, but we can just define it once. I am getting an error in the following program.
hello.c
#include <stdio.h>
#include "function.h"
extern int c;
int main()
{
int c;
c=10;
printf("%d\n",c);
printExternValue();
return 0;
}
function .h
void printExternValue();
function .c
#include "function.h"
#include "stdio.h"
extern int c;
void printExternValue()
{
printf("%d\n",c);
}
I expect this program to print out:
10
10
But it's not doing so since it's giving an error. I re-declared the variable c in the function.c file with the intention of using the value that is stored in the so called external storage.
Error: function.c:(.text+0x6): undefined reference to `c'
I am currently reading a PDF file from tutorialspoints which I think to be very redundant since the intention of creating a variable with the aggregate extern is useless. The right way this should be done is that they define the variables outside the function is that right?
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
Variable declread as
extern int c;
is an external declaration that potentially requires an external definiton. "External" in this case means "located outside of any function". Your c declared locally in main() does not fullfill that role.
Since you are using that externally declared variable c in your code you have to define it and define it only once.
You need
int c;
or
int c = 0;
or
extern int c = 0;
it one of your implementation files, at file scope. All of these are definitions. Any of them will define your variable.
Define your variable once in one of your files (to reserve space),
int c = 0;
Declare your variable references everywhere else (in all of your other files) (to reference said space),
extern int c;
But that could be confusing, so name them indicative of the 'global' use,
int glob_a, glob_b;
int glob_c;
float glob_f;
And declare your variable references everywhere else,
extern int glob_a, glob_b;
extern int glob_c;
extern float glob_f;
But you really want to avoid littering you namespace, so when you have a collection of globals, declare a struct that contains them (in a header file probably called globals.h),
typedef struct globals_struct {
int a, b;
int c;
float f;
} globals_t;
And once (in your file main.c that declares main()), you define the struct,
#include globals.h
globals_t globs;
And everywhere else, reference the space,
#include globals.h
extern globals_t globs;
Often, you will see a stanza such as this, where MAIN is only declared in one file,
#ifndef MAIN
extern globals_t globs;
#else
globals_t globs;
#endif
Use your globals,
int my_a = globs.a;
int my_b = globs.b;
int my_f = globs.f;
Notice how you have avoided needless namespace pollution?
Because extern just tells the compiler (actually the linker) that a variable is being defined elsewhere and needs to be linked against.

static keyword and external variables in C

I have the following piece of code where I define a couple of external (global) variables after the place in code where I need to use them.
In order to do so I use the keyword extern to declare them without reserving storage for them.
int main(int argc,char *argv[])
{
extern int a;
extern double b;
/* ...use the variables somehow... */
{
int a = 10;
static double b = 2.0;
if I do so, the compiler complains that I'm defining the b variable to be static (thus with internal linkage),when before I declared it to be extern.
But if I invert the order and define it before using it and declare it inside main ( which is otpional I know...) everithing is fine.
static double b = 2.0;
int main(int argc,char *argv[])
{
extern int a;
extern double b;
/* ...use the variables somehow... */
{
int a = 10;
so what if I'd like to use an external private variable (i.e. with internal linkage) before I define it? is it forbidden and why?
The extern keyword tells the compiler that the variable we refer to is located in a different translation unit (another source file basically), while the static keyword means that the variable (in the case of global variables) is local to the current translation unit and cannot be seen in other source files, so it makes no sense to use the two keywords together.
Once you have declared b as global in the same file, it is visible in main and there is no need to declare it again, you just can use it.
If on the other hand it is declared in a different translation unit as a global variable, the extern keyword becomes necessary.

How does the local static variables are stored

If I declare a global variable as static it will be stored in data segment. And all the functions in that file can access it. no issues so far....
If, inside a function if we declare a static variable, as shown below:
int foo()
{
static int a;
.
.
}
so this variable "a" also stored in data segment (please correct me if I am wrong).
my question is, if the global static variable which is stored in data segment is accessible across the functions.
But the static variable which is defined inside the function which is also stored in data segment, is not accessible across the functions, why?
That is because of SCOPE
Scope is the region or section of the code where a variable can be accessed. There can be
File Scope
Function Scope
Block Scope
Program Scope
Prototype Scope
Example
#include<stdio.h>
#include<conio.h>
void function1()
{
printf("In function1\n");
}
static void function2()
{
printf("In function2\n");
{
int i = 100;
Label1:
printf("The value of i =%d\n",i);
i++;
if(i<105)
goto Label1;
}
}
void function3(int x, int y);
int main(void)
{
function1();
function2();
getch();
return 0;
}
In the example,
‘function1()’ has ‘Program Scope’.
‘function2()’ has ‘File Scope’.
‘Label1’ has ‘Function Scope’. (Label names must be unique within the
functions. ‘Label’ is the only identifier that has function scope.
Variable ‘i’ has ‘Block Scope’.
Variable ‘x’ and ‘y’ has ‘Prototype Scope’. There cannot be two
variables with the name ‘x’ or ‘y’ in the function parameter list.
Its just a rule the compiler and linker implement. For one thing you can have multiple static variables in different functions with the same name.

Resources