Static variable inside shared library

My question is about a static variable (static void *) created inside the shared library (let it be called this library "S"), but the internal variable is not shown externally, but every API call depends on it. Now think about the case when a program (call its main program), links to two other shared libraries, and each of them is connected to the S library. Now, what happens with this static variable for our main program? Does he have one instance? Two?

+3
source share
3 answers

Assuming that your static variable is defined in only one translation unit, it will exist only once, since the shared library is loaded only once in the process.

This will be more difficult if the mix is shared and static .

+3
source

Sumy's answer is correct. There will be only one instance of a static variable. This is also due to the fact that having static globals in shared libraries can be a huge problem. One real-world example where this can happen:

  • Apache web server that loads the following modules:
    • mod_php which is associated with
      • libxml2
    • mod_perl that loads
      • libxml2

, - PHP- , libxml2, Perl . , . .

( libxml2 .)

+6

, .

, (, , ) , .

You can prove it to yourself by declaring a global static variable in the header file, and then include this header file in several different source files. Try setting it to a different value in each source file, and you will see that this variable stores its value in each source file.

0
source

All Articles