在 C++ 中包含静态变量的库的多重链接中静态变量的行为到底是什么?

问题描述 投票:0回答:1

让我们想象一个场景

  • 可执行文件 (A),
  • 一个 dll (B),以及
  • 静态库 (C)。

A 和 B 都链接 C 并包含其头文件。 现在 C 中存在一个类:

class Foo {
   static const Bar& getShared(); // just defined in cpp returning _sharedVarible
   static Bar _sharedVarible;
};

这是否意味着在这种情况下,如果我在 A 和 B 中分别调用

sharedVariable
,我将在 A 和 B 中拥有
getShared()
的多个副本?

如果 C 也是一个

.dll
那么情况会是一样的,或者因为 C 是 dll 我对于 A 和 B 都只有一个
sharedVariable
的唯一实例?

最后一个 - 如果两种情况都会导致该变量的多个副本,则此解决方案中 C 仍然是

.lib
:

// in some header of C...
extern Bar sharedVariable;

// in some cpp of C...
sharedVariable = Bar();

最终为我提供了 A 和 B 的一个唯一的全局

sharedVariable
实例?在最后一种情况下,C 是
.lib
还是
.dll
有关系吗?

c++ static static-linking dynamic-linking extern
1个回答
0
投票

你很困惑

  • static
    静态数据成员,以及
  • static
    内部链接

Foo
的示例中,
static Bar _sharedVarible;
根本没有定义,因此尝试链接它只会是一个错误。 从这里,您有两个选择,假设该类具有外部链接(不在未命名的命名空间中):

  1. _sharedVariable
    定义为
    inline
    (课堂内或课堂外)
  2. 在源文件中定义
    _sharedVariable
    (外部链接)

无论哪种情况,C 在整个库中都只有一个

_sharedVariable
的副本,并且该版本将在链接时被 A 和 B 使用。

静态数据成员有多个副本的唯一场景是:

namespace {

struct Foo {
   static Bar _sharedVarible;
};

Bar Foo::_sharedVariable;

}

现在,假设,如果此代码位于标头中,并且 A 和 B 包含此标头,则将存在

Foo
和成员
_sharedVariable
的唯一副本。

© www.soinside.com 2019 - 2024. All rights reserved.