What happens to static variables when libraries are statically linked

后端 未结 3 2041
你的背包
你的背包 2021-02-09 12:21

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

3条回答
  •  天命终不由人
    2021-02-09 13:12

    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).

提交回复
热议问题