Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c++ - Are inline variables unique across boundaries?

This is a follow up of this question.
As mentioned in the comments to the answer:

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.

Moreover, from the answer itself:

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.

In other terms, it isn't clear if an inline variable is guaranteed to be unique across boundaries when shared libraries are involved. Someone proved empirically that it works on some platforms, but it isn't properly an answer and it could just break everything on other platforms.

Is there any guarantee regarding the uniqueness of an inline variable when it is used across boundaries or is it simply an implementation detail that I should not rely on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how I interpret the standard. According to basic.link/1:

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

It doesn't say anything about static linking nor dynamic linking. A program is translation units linked together. It doesn't matter if the linking is done in two steps (first create a .dll/.so, and then the dynamic linker links all dynamic libs + executable together).

So, in my interpretation, it doesn't matter whether a program is dynamically or statically linked, the implementation should behave the same: a class static variable should be unique (no matter whether it's inline or not).

On Linux, this is true.

On Windows, this doesn't work in all circumstances, so in my interpretation, it violates the standard in these circumstances (if you create a separate .dll, which contains the static, non-inline variable, and all other .dll's and the exe refers to this variable, it works).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...