0

test1.hpp

struct obj{
obj(){}
~obj(){cout<<"destroyed"<<endl;}
};
static obj x;

test1.cpp

#include "test1.hpp"

main.cpp

#include "test1.hpp"
int main(){...}

the destructor is getting called twice, why is this happening? gcc-7.5.0 os-ubuntu

Abhinav Singh
  • 302
  • 3
  • 15

2 Answers2

3

why is this happening?

Because the variable is declared static. This means that the variable has internal linkage. Which means that each translation unit has their own object. You have defined the variable in two translation units, and therefore you have two objects.

If you didn't want this, then the variable shouldn't be static. An easy solution is to declare it inline instead. This allows it to have external linkage while still being defined in the header.

P.S. Be very careful of Static Initialisation Order Fiasco. Try to avoid variables of static storage when you can, especially those in namespace scope.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

You have two static variables with the internal linkage due to defining the corresponding object in the header

struct obj{
obj(){}
~obj(){cout<<"destroyed"<<endl;}
};
static obj x;

This header is included in two modules test1.cpp and main.cpp. So each module has its own static variable x.

If you want to have one object with the external linkage then declare it in the header like

extern obj x;

and define it in one of modules like

obj x;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335