Search code examples
cstaticextern

Global static variables shared in multiple source files


While learning about extern and static variables in C/C++, I came across this answer.

Maybe I'm missing some point, but this answer raised doubts about a code of mine.

Suppose I have the following files:

  • header.h
static int global_foo = -1;

void doSomething(void);
  • source1.c
#include "header.h"

void doSomething(void) {
  global_foo = 1;
}
  • main.c
#include "header.h"

int main(void) {
  doSomething();
  printf("%d\n", global_foo);
}

What exactly is the output of the printf in the main function? My interpretation is that since global_foo is included two times, there will be two distinct global_foo, and therefore one such change will affect only the global_foo of the file that it belongs to.


Solution

  • Your assessment is correct.

    Because global_foo is declared static, each source file has its own distinct variable by that same name, and a change to one does not affect the other.

    Because of this, the program will print -1, since the global_foo in main.c is unchanged.