c++ - 内联变量是否跨边界唯一?

标签 c++ shared-libraries language-lawyer c++17 inline-variable

这是 this question 的后续事件.
如答案评论中所述:

An inline variable has the property that - It has the same address in every translation unit. [...] Usually you achieved that by defining the variable in a cpp file, but with the inline specifier you can just declare/define your variables in a header file and every translation unit using this inline variable uses exactly the same object.

另外,从答案本身来看:

While the language does not guarantee (or even mention) what happens when you use this new feature across shared libraries boundaries, it does work on my machine.

换句话说,当涉及共享库时,内联变量是否能保证跨边界唯一并不清楚。有人凭经验证明它在某些平台上有效,但它不是正确的答案,它可能会破坏其他平台上的一切。

当跨边界使用内联变量时,它的唯一性是否有任何保证,或者它只是一个我不应该依赖的实现细节?

最佳答案

这就是我对标准的解释。根据basic.link/1 :

A program consists of one or more translation units linked together.

它没有说任何关于静态链接或动态链接的内容。程序是链接在一起的翻译单元。链接是否分两步完成都没关系(首先创建一个.dll/.so,然后动态链接器将所有动态库+可执行文件链接在一起)。

因此,在我的解释中,无论程序是动态链接还是静态链接,实现都应该表现相同:类静态变量应该是唯一的(无论它是否内联)。

在 Linux 上,这是真的。

在 Windows 上,这并不适用于所有情况,因此在我的解释中,它在这些情况下违反了标准(如果您创建一个单独的 .dll,其中包含静态、非内联变量和所有其他 . dll和exe引用这个变量,它可以工作)。

关于c++ - 内联变量是否跨边界唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374558/

相关文章:

c++ - 在 C++ 中访问 Windows 任务栏图标

c++ - C 创建一个给定大小的文件

C++ 比较指向不同类型的指针?

linux - 从内存中卸载共享库

c++ - C++中的顶级是什么?

android - Cocos2d-x onTouchMoved 在没有移动发生时调用

c++ - 如何使用库的头文件生成 libfoo.sym 文件以与 libtool -export-symbols 一起使用?

linux - 有没有一种方法可以使Linux中的进程静态化而不需要重新编译它?

c++ - 修改 std::for_each 中的容器

c++ - 嵌套类的模板模板参数的可变类型模板参数和非类型模板参数如何相互约束?