Static data in dynamically loaded C++ shared libs on linux
Martin v. Loewis
martin@mira.isdn.cs.tu-berlin.de
Wed Dec 1 01:03:00 GMT 1999
> According to the egcs source, for static objects within a function, a
> local function is generated and registered as an exit handler, using
> atexit() (See egcs-*/gcc/cp/decl.c:expand_static_init()). This leads
> to the problem that this function's memory address is invalid when
> exit() tries to invoke it.
Thanks for your bug report. This is a know limitation of g++, although
it is not strictly a bug.
The behaviour you see is mandated by the C++ standard. Consider
void foo(){
static Class a;
}
void bar(){
static Class b;
}
void foobar();
int main()
{
foo();
atexit(foobar);
bar();
}
In this code, initialization order of a and b is not known at compile
time; it is not known whether they are initialized at all. Regardless,
the standard requires that objects are destroyed in reverse order of
construction. Furthermore, it requires that this also interleaves with
calls to atexit functions.
I.e. in above program, after main is complete, the following should
happen:
1. destructor of b,
2. call to foobar,
3. destructor of a
About the only way to implement this correctly is to use atexit. Of
course, this has undesirable side effects on libraries unloaded with
dlclose.
This is not a bug in the strict sense, because nobody says that this
should work. The C++ standard does not mention dlclose, the dlclose
definition does not mention atexit or C++, and the GCC documentation
does not document your code as working.
So the limitation is that you can't use function-static objects in a
shared library that you close with dlclose. You can either live with
that, or find some way to work around it.
Regards,
Martin
More information about the Gcc-bugs
mailing list