静态链接库时静态变量会发生什么 [英] What happens to static variables when libraries are statically linked

查看:91
本文介绍了静态链接库时静态变量会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个库(A)实现单例模式(它的实现中有一个静态变量).

Let's say I have library (A) implementing the singleton pattern (it has a static variable in its implementation).

(A)库被编译为静态库.

现在,让我说我的对象是:

Now, let's say I have in my probject:

  • (B),另一个与(A)静态链接的静态库.
  • (C),另一个与(A)静态链接的静态库.
  • (D),这是一个与(B)(C)链接的顶级程序.
  • (B), another static library linking statically with (A).
  • (C), another static library linking statically with (A).
  • (D), a top level program linking with (B) and (C).

最后,我的单身人士真的是一个单身人士吗(我的变量真的是静态的)吗?(B)(C)是否在(A)中使用相同的静态变量(是否是唯一的)?还是(A)被静态链接两次的事实嵌入了(A)的代码两次,最终以我来自(A)在最终的二进制代码中出现两次?然后,如果(B)修改了静态变量值,那么(C)会看不到更改吗?

In the end, is my singleton really a singleton (and my variable really static)? Are (B) and (C) seing the same static variable from (A) (is it unic)? Or does the fact that (A) was statically linked twice embedded (A)'s code twice ending up with my static variable from (A) appearing twice in the final binary code? Then if (B) modifies the static variable value, (C) would not see the change?

注意:我遇到了将项目库更改为静态链接而不是动态链接的经历.我只是想知道我做错了什么,还是正常的已知行为.

Note: I experienced that when changing the libraries of project to be linked statically instead of dynamically. I'm just wondering if I did something wrong, or if that's a normal known behaviour.

推荐答案

首先:

(B)和(C)不能链接到(A).静态库是编译的,不是链接的.在构建(B)和(C)时,编译器可能需要查看(A)中的某些定义,但不要将其与链接混淆.(A)的代码不会复制到(B)或(C)中.

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

其次:

(D)必须链接到(A),(B)和(C).这意味着您只能在(D)中获得(A)代码的一个副本.

(D) will have to link against (A), (B) and (C). That means you get only one copy of (A's) code in (D).

动态链接库/共享对象:

如果(B)和(C)分别是dll/sos,则这当然会有所不同.DLL是链接的,因此,如果将(B)和(C)编译为dll,并针对(A)链接它们,那么您将在(B)和(C)中都有(A)代码的单独副本.

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

(B)和(C)是否在(A)中使用相同的静态变量

Are (B) and (C) seing the same static variable from (A)

这取决于您的变量是否具有外部或内部链接.以下头文件包含带有内部链接的静态int变量.这意味着每个包含此文件的翻译单元都将获得它自己的 myVariable 副本.

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;

这篇关于静态链接库时静态变量会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆