Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to understand static behaviour

Tags:

c++

c

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?

like image 741
Rasmi Ranjan Nayak Avatar asked Dec 01 '25 05:12

Rasmi Ranjan Nayak


2 Answers

static variables has internal linkage which means each translation unit gets its own copy.

So in your program each .cpp file which includes t.h has 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 .cpp file, because the object in the other .cpp file is a different object. Why should it change?

But when you change it to int abc (i.e don't make it static), 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, static objects 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.

like image 95
Nawaz Avatar answered Dec 02 '25 20:12

Nawaz


When the preprocessor is done with your code, main.c looks like

// omitted stuff from stdio
static int abc;
int main()
{
    abc++;printf("%d \n", abc);
    test();
}

and test.c looks like

// omitted stuff from stdio
static int abc;
void test()
{
    abc++;
    printf("%d \n", abc);
}

So each file contains its own variable abc that is not accessible from the other.

One solution would be to change t.h to

#ifndef __t_h__
#define __t_h__
extern int abc;
#endif

and then change main.c to

#include <stdio.h>
#include "t.h"
int abc;
int main()
{
    abc++;printf("%d \n", abc);
    test();
}

You can think about it like this: there's now only one int abc in your program, in main.c but test.c knows about its existence because the extern int abc tells test.c that somewhere else in the project there is an integer called abc that it will be able to find at link time.

like image 27
Wernsey Avatar answered Dec 02 '25 21:12

Wernsey