Let\'s say I have library (A)
implementing the singleton pattern (it has a static variable in its implementation).
(A)
library is compiled as a
static linked library, and static variables are not related.
A static variable, is not visible outside the current compilation scope (no symbol name is created in the .o file, so no other .o files can find that variable via the symbol name).
This means that the variable
static int foo; can exist in every compilation scope, and each one will be uniqe
First of all:
(B) and (C) do NOT link against (A). Static libs are compiled, not linked. When building (B) and (C) the compiler might need to see certain definitions from (A) but do not confuse this with linking. (A's) code is not copied into (B) or (C).
Secondly:
(D) will have to link against (A), (B) and (C). That means you get only one copy of (A's) code in (D).
Dynamic-link Library/Shared Object:
This of course would be different if (B) and (C) were dlls/sos instead. Dlls are linked and so if you build (B) and (C) as dlls and link them against (A) then you would have a separate copy of (A's) code in both (B) and (C).
Are (B) and (C) seing the same static variable from (A)
This depends on if your variable has external or internal linkage. The following header file contains a static int variable with interal linkage. This means that every translation unit that includes this file will get it's own copy of myVariable
.
//MyHeader.h
#pragma once
static int myVariable = 0;
Your static variable is really static. I suspect that even if (B) links (A), (B) does not pick up it's own copy of (A) - instead it contains information that (A) should be linked.
It's however possible to compile same source code with static variable in two libraries - for example:
test.cpp:
int g_myGlobal = 23;
and compile it in (A) and (B) static libraries, but then when linking whole application or dll - you will get linker error about double defined static variable.
If you however declare variable with static keyword:
test.cpp:
static int g_myGlobal = 23;
Then if same source code is linked from (A) and (B) - it will be compiled and linked ok, but as a result you will have two instances of g_myGlobal variable (which can be even different).