Possible bug in binutils for MinGW-w64 related to linking weak symbols
Martin Storsjö
martin@martin.st
Thu Mar 19 15:53:32 GMT 2026
On Thu, 19 Mar 2026, Martin Storsjö wrote:
> On Thu, 19 Mar 2026, Martin Storsjö wrote:
>
>> When you use a declaration of a weak symbol (which means that the symbol
>> either may be defined, or may be undefined, when it essentially is a null
>> pointer), then the symbol "bar" points at an absolute symbol with the
>> address zero. The idea here is that if nothing else overrides the symbol,
>> then it uses the fallback value of absolute zero (and in that case, the
>> user should check if it is null before referencing it).
>
> Sorry, I misremembered one detail here. The default symbol it points at
> isn't an absolute zero symbol, it's an undefined symbol.
Sorry again - I misinterpreted the output; what I said initially is indeed
right - for a declaration (not definition) of a weak symbol, the default
is an absolute null pointer.
And actually, using __attribute__((weak)) on the declaration when using
the symbol isn't beneficial and consistent; it makes each object file
using the symbol provide their own null pointer default for it. This means
that depending on linking order, you either get a definition or a the null
pointer default.
So if the declaration is weak, in translation units that use the symbol,
then each of those uses also need to check if the symbol actually is
nonnull.
It turns out that LLD (LLVM's linker) also does the same as GNU ld here;
if the first object file is the one using it, we end up crashing in the
same way here.
So IMO requiring the declarations to use weak isn't a fix, that makes it a
gamble on which symbol the linker happens to see first. (However in
practice, I haven't ever run into this combination in practice in code in
the wild - using weak definitions in combinations with weak declarations
doesn't seem to be common.)
We can avoid that gamble in LLD, by implementing preference between the
different weak aliases like this though:
https://github.com/mstorsjo/llvm-project/commit/lld-weak-prefer-nonnull
// Martin
More information about the Binutils
mailing list