On Linux, why does a destructor run twice in a shared instance of a global variable in C ++?

On Linux, I have generated C ++ code from a static library that defines a global variable. One instance of this global variable is shared between two shared libraries that reference its symbol.

When the process terminates and the static completion phase starts, I see that the destructor on this shared instance starts twice! Presumably once per library at each load.

This question is closely related to another that I recently saw here: a related question . This is similar to the same behavior, but it is not discussed why this is happening.

Does anyone know a theoretical explanation for this behavior?

+7
c ++ linux global-variables destructor shared-libraries
source share
2 answers

If you take a bare pointer and put it in a smart pointer (twice), it will collapse twice, once when for each basket the refpount drops to zero.

So, if you pass the bare pointer to both libraries, this will do it. Each of them places it in a common pointer object, and each of them destroys it. If you see a stack backtrack during dtor, this should show that this happens in both libraries.

+2
source share

C ++ has a rule called the "Single Definition Rule":

Each program must contain exactly one definition of each non-built-in function or object that is used in this program; no diagnostics required. The definition can be explicitly displayed in the program, it can be found in the standard or user-defined library, or (if necessary), it is implicitly defined (see 12.1, 12.4 and 12.8).

Wikipedia has an article that explains this in more detail.

You did not have the code in your question, so I cannot be sure of your case, but in the question that you linked to , the example in the question defined the same variable in two shared libraries. This violated the β€œOne Definition” rule, which apparently depends on the completion strategy of the dynamic linker, with the result that the destructor is called twice.

0
source share

All Articles