static int in header file is duplicated?

Hi, I stumbled upon a situation I don't understand,

I'm learning C++ through Bruce Eckel's C++ book.
In chapter 10, the 10th exercise is:
"Prove that file static variables in header files don’t clash with each other when included in more than one cpp file."

I can proof that file static variables don't clash, but I don't understand "why". Why does every call to a file static variable from a different file create new storage for that variable?

This is what I wrote:

1
2
3
4
5
6
7
8
9
//Header2.h

#ifndef Chapter5_Header2_h
#define Chapter5_Header2_h
static int behold;

void f();

#endif 


1
2
3
4
5
6
7
8
//File.cpp

void f() {
    using namespace std;
    cout << "f() in File.cpp has been called!\n";
    behold = 22;
    cout << "behold is called in File.cpp, value: " << behold << endl;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
//main.cpp

#include <iostream>
#include "Header.h"
#include "Header2.h"

using namespace std;

int main() {
    behold = 12;
    behold++;
    f();
    cout << "behold is called in Main.cpp, value: " << behold << endl;
} ///:~ 



f() in File.cpp has been called!
behold is called in File.cpp, value: 22
behold is called in Main.cpp, value: 13


I was expecting that there would just be 1 version of "int behold", that would change from whatever cpp-file I was modifying it. Instead, there appear to be duplicate versions of that variable, each having it's own value. Why does it have this behaviour?
static variables have internal linkage. So they are visible only in one compilation unit. Each compilation unit has its own object of the static variable.
Shortly speaking, yes, it is duplicated in each module where the header is included.
Last edited on
Aaah, I mixed up the two different meanings of "static", thanks, I get it now.
Topic archived. No new replies allowed.