Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable inside shared library

My question is about static variable (static void*) created inside shared library (let's call this library 'S'), but it's an internal variable not shown outside, but every call of API depends on it. Now let's think about a case, when a program (let's call it main program) links to another two shared libraries and every one of them is linked with library S. Now what happens to this static variable for our main program? Does it have one instance? Two?

like image 644
zoska Avatar asked Oct 21 '25 04:10

zoska


1 Answers

Suma's answer is correct. There will only be a single instance of the static variable. This is also why having static globals in shared libraries can be a huge problem. One real-world example where this can happen:

  • Apache webserver which loads the following modules:
    • mod_php which is linked against
      • libxml2
    • mod_perl which loads
      • libxml2

Now if some PHP code modifies a global setting like a parser option in libxml2, the Perl code will also see these changes. This can lead to bugs that are extremely hard to diagnose. So you should avoid global state in your shared libraries at all cost.

(With libxml2 you can make most settings locally these days.)

like image 176
nwellnhof Avatar answered Oct 23 '25 20:10

nwellnhof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!