Story of Static Variable in CPP/C++. Why multiple instances of static are created.

asheesh kumar singhal
2 min readFeb 28, 2021

We all know that static variables and global variables are declared on the Data segment in memory and their lifetime is throughout the program.
We also know that static variables are local to the translation units and global variables are available in all the translation units. But what this translation unit means???

So I went and to check how static and global variables are different and how this translation unit thing works?

lets create 2 class: class A and class B in 2 different header .h and .cpp files.
A.h

#include<iostream>
using namespace std;

class A{
public:
A();
}

A.cpp

#include<iostream>
using namespace std;

A::A()
{
cout<<”constructor of A called”<<std::endl;
}

B.h

#include “A.h”

static A a;
class B
{
public:
B();
}

B.cpp

#include<iostream>
using namespace std;
B::B()
{
cout<<”constructor of B called”<<std::endl;
}

main.cpp

#include “A.h”
#include “B.h”

int main
{

B b();
return 0;

}

When you built the above program and run it the output is :

constructor of A called
constructor of A called
constructor of B called

looking weird??
Why?
because we said that static has life throughout the program but is local to a translation unit. ie a .cpp file or .o (object)file

Since the object of A a is available in 2 translation units B and main. hence two instances of A are generated.
What I have seen that at each include of “b.h” a new instance of A will be created.

To avoid multiple instances of A, we can either use a singleton class or we should create static instances in .cpp files.
.Cpp files are the files that will not be included anywhere and we can avoid the trouble of multiple instances.
It also becomes quite confusing as to which memory location of the static variable we will point to.

Also to create a global variable extern keyword should be used. instances created without static member variable will result in linker error saying multiple instances of A found.

--

--