I wrote in
// In file t.h
#ifndef __t_h__
#define __t_h__
static int abc;
#endif
—
//In main.c
#include <stdio.h>
#include "t.h"
int main()
{
abc++;printf("%d \n", abc);
test();
}
– –
//In test.c
#include <stdio.h>
#include "t.h"
void test()
{
abc++;
printf("%d \n", abc);
}
When I run the project I found the output of abc is 1 and 1.
But when I change it to int abc in t.h. The output of abc = 1 and 2.
Why static is not retaining the value when the control reaches to test.c file.
If it won’t retain then why should not it provide an error as the static variable can not be shared between/among the files?
staticvariables has internal linkage which means each translation unit gets its own copy.So in your program each
.cppfile which includest.hhas its own copy of the static variable, which in turn means, there are two objects in the memory. You can try printing their addresses to confirm this, as they will be different.That makes the situation pretty simple: if you change the object in one
.cpp, it doesn’t reflect in the other.cppfile, because the object in the other.cppfile is a different object. Why should it change?But when you change it to
int abc(i.e don’t make itstatic), then each translation unit has same object. If you change it in one file, it will be reflected in other file also, as expected.As for sharing, then yes,
staticobjects can be shared between two functions in the same translation unit, but they cannot be shared between two translation units.Search for translation unit on this site, you will get many topics on it. Read them, then you will understand it fully.