C++ Logo

std-discussion

Advanced search

Re: Global array of objects over multiple files

From: Federico Kircheis <federico_at_[hidden]>
Date: Sun, 20 Oct 2024 08:18:33 +0200
On 20/10/2024 07.58, Thiago Macieira via Std-Discussion wrote:
> On Saturday 19 October 2024 12:59:31 GMT-7 Federico Kircheis via Std-
> Discussion wrote:
>> As an example, a class that logs in the destructor it's address and a
>> string:
>>
>> https://godbolt.org/z/sb8n8fn1a
>
> This one has a ODR violation: the symbol "instance" is defined in two TUs. It's
> ill-formed.

AFAIK it is not an ODR violation.
There is one definition and multiple declarations, it is not UB.

>
>> Same class, slightly different context:
>>
>> https://godbolt.org/z/Thv8xhc6Y
>
> Also ODR violation for the same reason.

In this cases, there is one definition and one declaration in one TU.

>
>> Another example that shows the same behavior
>>
>> https://godbolt.org/z/ecPPq8vns
>
> This is the exact same code as the previous one: lib0.cpp is linked twice into
> your executable, therefore ODR violation.

lib0.cpp is linked once in the dynamic library lib1, once in the dynamic
library in lib2, and 0 times in main (and main uses lib1 and lib2).
lib0 has only one declaration.

If lib1,lib2 where applications and main would communicate through IPC,
then there would be no issues.

If lib1 and lib2 where static libraries (or to put it another way, if
they where not separate libraries), there would be no issue, since there
is only one declaration in the whole code basis.

Thus it does not like ODR to me, because there is one definition, and in
the last two examples only one declaration.

But even if it where an ODE, how do you fix those issue with dynamic
libraries?

Assuming that the author of lib0 is not the same of lib1 and lib2, who
needs to change what?

In all the examples, the global variable is an implementation detail, it
is not even used directly outside of lib0.

Received on 2024-10-20 06:18:39