Problem with UNIX/Linux Shared Libraries and Global variables ...

V

viraj.kadakia

I observe a behavior with shared libraries (.so) and global variables
that I cannot understand ...
I'd appreciate if someone can explain the behavior ..

Scenario 1:
a> Test is an executable on Solaris/Linux built from main.o (main.cpp)
b> Test dynamically loads a shared libraires mylib1.so and mylib2.so
both built from mylibsrc.o (mylibsrc.cpp)
c> mylibsrc.cpp contains a global variable 'int MyGlobal' that is non
static and not extern (simply int MyGlobal)
d> I have extern C Set and Get functions in mylibsrc.cpp to access
MyGlobal
e> Under these circumstatnces, when I run Test, MyGlobal seems to have
two instances in memory, one for each .so
Their runtime values (modified by dlsym(handle, Set)) and
addresses are different as expected.

Scenario 2:
a> Everything is same as Scenario 1 except ..
b> main.cpp (Test) also has a global non-static, non-extern variable
'int MyGlobal'
c> Now when I run Test, all 3 MyGlobal(s) (in Test, mylib1.so and
mylib2.so) are the same memory address and same value.

Why is the behavior under these to scenarios different ?
I expect that MyGlobal in main.cpp should have its own instance ...

p.s. I use -fPIC / -KPIC and -Bsymbolic while generating the .so(s)

Thanks in advance ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top