0

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
José Joaquim
  • 103
  • 2
  • 9
  • 2
    Despite the name, `global_foo` isn't actually a global variable. It *is* a file scope variable. To create a true global variable, you need to define the variable in a .c file as `int global_foo = -1`. Then the header file should declare the variable as `extern int global_foo;` – user3386109 May 02 '20 at 23:21

2 Answers2

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

Global variables have static storage duration anyway so there's no need to include the static qualifier to explicitly state its storage duration. When you declare a global variable as static within a translation unit you are just saying that it has internal linkage within that translation unit. This means it can only be identified by its name within the translation unit.

So, if you declare a variable as static in a header file, every translation unit that includes it gets its own copy of the variable that is different from all the others.

If you have a function that returns the address of the variable, i.e.

int *getStaticAddress () 
{
    return &static_var; 
}

You can use that to access the variable outside the translation unit.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85