views:

172

answers:

2

On Linux I have some generated C++ code from a static library that defines a global variable. A single instance of this global variable is shared between two shared libraries that refer to its symbol.

When the process shuts down and the static termination phase is run, I see that the destructor on this shared instance is run twice! Presumably once per library as each unloads.

This question is closely related to another I saw recently here: related question. This sounds like the same behavior, but there is no discussion about why it is happening.

Does anybody know the theoretical explanation behind this behavior?

+2  A: 

If you take a naked pointer and place it in a smart pointer (twice), it will destruct twice, once for each container refcount falling to zero.

So, if you pass the naked pointer into both libraries, that would do it. Each one puts it in a shared pointer object and each of those does the destruction. If you can see the stack backtrace during the dtor, that should show it happening in both of the libraries.

Mark0978
Using any regular debugger, it should be easy to check the call stack backtrace and find out who is calling this destructor.
Vargas
A: 

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

Every program shall contain exactly one definition of every non-inline function or object that is used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see 12.1, 12.4 and 12.8).

Wikipedia has an article that explains this in more detail.

You haven't posted code in your question, so I can't be sure about your case, but in the question you linked to, the example in the question was defining the same variable in two shared libraries. This violated the "One Definition Rule", which apparently the dynamic linker's finalization strategy depends on, causing the destructor to be called twice.

Jim Blandy