Skip to content

support external weak symbol references #1917

@andrewrk

Description

@andrewrk

Accepted Proposal


We need a way to declare an external symbol, but one that should be NULL rather than a linker error if the symbol is never supplied.

One use case is to detect if an executable is dynamically linked, like this: https://git.musl-libc.org/cgit/musl/tree/src/env/__init_tls.c#n89:

extern weak hidden const size_t _DYNAMIC[];
...
		if (_DYNAMIC)

When an external weak symbol is not linked, there actually is no address for it. So representing it as an optional type is incorrect. What we need is an optional pointer to the symbol. For that I propose a builtin function:

@externWeak(comptime name: []const u8, comptime PointerType: type) ?PointerType

PointerType could be any pointer type. The reason we supply the pointer type and not the element type is so that the default alignment can optionally be overridden by using a pointer type with an explicit alignment.

With this proposal the C code above could be represented in Zig like this:

if (@externWeak("_DYNAMIC", [*]usize) != null)

The result value of the function is a runtime-time known value, however it is eligible to participate in simple global variable initialization expressions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions