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?
-
there 'll be one instance since you declared it as a static onetarzanbappa– tarzanbappa2014-02-24 09:39:38 +00:00Commented Feb 24, 2014 at 9:39
-
Related: stackoverflow.com/questions/3186926/…Suma– Suma2014-02-24 09:58:12 +00:00Commented Feb 24, 2014 at 9:58
-
@Suma How does answer to question you mentioned help me?zoska– zoska2014-02-24 12:36:53 +00:00Commented Feb 24, 2014 at 12:36
-
It is related in that it shows one scenarios, where linking to two shared libraries B and C both linking statically to library A can cause a variable in A to exist twice.Suma– Suma2014-02-24 13:51:31 +00:00Commented Feb 24, 2014 at 13:51
-
In this case there is no static linking.zoska– zoska2014-02-24 16:10:30 +00:00Commented Feb 24, 2014 at 16:10
3 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
- mod_php which is linked against
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.)
Comments
The compiler creates a different instance for every global static variable, even when you have several such variables with identical names.
In fact, the compiler (or possibly, the preprocessor) implicitly changes the name of every such variable, according to the name of the source file which declares it.
You can prove this to yourself by declaring a global static variable in a header file, and then include this header file in several different source files. Try to set it to a different value in each source file, and you'll see that this variable retains its different value in each source file.