Hi There,

I'm not sure if this is the case of a misplaced compiler option, or
there is a bug in the compiler, but I get unexpected output when I use
the same class with a static member in both a shared library and an
executable, compiling under g++ on Linux.  Perhaps the best way to
explain is with the aid of some code ... please bare with me !!

If I create a class that I want to use in my executable and a shared
library:

class CommonElement
{
public:
    CommonElement(int i) { m_static = i; }
    void PrintIt() { printf("My Value= %d\n", m_static);

private:
    static int m_static;  // Init to zero in cpp.
};

If I then decide to create my simple shared library with a single
exported function...

extern "C" void LibraryFn()
{
    CommonElement loc(99);
    loc.PrintIt();
}

And I also find it useful to do some work in my executable, that also
loads in the shared library dynamically using dlopen(), etc.

int main (int argc, char* argv[])
{
    CommonElement exeElem(10);
    // Use dlopen/dlsym to obtain LibraryFn()

    exeElem.PrintIt();   // Display exe static value.
    LibraryFn();            // Call library function to display output.
    exeElem.PrintIt();   // Print out our exe static value again.
}

If I compile this to generate the shared library and executable using
the -fPIC option I get the following output:

My Value= 10;
My Value= 99;
My Value= 99;

However, The output I would expect is:
My Value= 10;
My Value= 99;
My Value= 10;

If I compile this without the -fPIC option I get the output I expect,
but I am forced to use -fPIC on a 64 bit machine, and after all .. I
think that is the right think to do !

Can anyone please help with this?  It would be much appreciated.  It
appears I end up using the same static member, even though it appears
in the symbol table of the shared library I create !

_______________________________________________
help-gplusplus mailing list
help-gplusplus@gnu.org
http://lists.gnu.org/mailman/listinfo/help-gplusplus

Reply via email to