What happens to static variables when libraries are statically linked

后端 未结 3 1970
你的背包
你的背包 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

    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;
    

提交回复
热议问题