-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
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.