Search code examples
cglobal-variables

Is there anyway can create a "new" global variable each time I call a function in C source file?


Test is on 32-bit Linux x86, I use gcc 4.6.3.

I have two C source files, which are main.c and foo.c. They look like this (I simplified this problem):

main.c

extern void foo(void);

void main()
{
    foo();
    foo();
}

foo.c

static int g = 0;
int g1 = 0;

void foo()
{
  printf("%d\n", g);
  g = 123;
  printf("%d\n", g);

  printf("%d\n", g1);
  g1 = 123;
  printf("%d\n", g1);
}

The result is :

0
123
0
123
123
123
123
123

So my question is:

Is there any way that, each time I call function in foo.c, a new global variables will be initialized? and the correct output would be:

0
123
0
123
0
123
0
123

I am not familiar with C, however, I am asked to make a source code translation tool towards C code, someone designed how to implement that tool somehow, leaving this weird problem to me.

Could anyone give me some help?


Solution

  • Reinitialize the variables at the start of foo:

    void foo()
    {
      g = 0;
      g1 = 0;
    
      printf("%d\n", g);
      g = 123;
      printf("%d\n", g);
    
      printf("%d\n", g1);
      g1 = 123;
      printf("%d\n", g1);
    }
    

    This way, g and g1 are set to 0 each time foo is called (and then foo sets them to other values).