zig icon indicating copy to clipboard operation
zig copied to clipboard

Proposal: Add linkname in addition to linksection

Open ikskuh opened this issue 1 month ago • 8 comments

Right now, exported and imported symbols in Zig use verbatim the name that is given when using export fn/extern fn or use a much more complex scheme when using @export/@extern.

Problem

So if i want to export (or import) a function with another name than i want to have it in Zig, i have two options:

// import
extern fn SDL_CreateWindow(…) …;
pub const createWindow = SDL_CreateWindow;

// export
export fn SDL_CreateWindow(…) … {}
pub const createWindow = SDL_CreateWindow;

or

// import
pub const createWindow = @extern(
    *const fn(…) callconv(.C) …,
    .{ .name = "SDL_CreateWindow" },
});

// export
pub fn createWindow() callconv(.) … { … }
comptime {
    @export(
        createWindow,
        .{ .name = "SDL_CreateWindow" },
    );
}

Both options feel clunky when i only want to change the name of the emitted symbol, so a C library will have a nice prefixed variant that doesn't clash names, and the Zig variant feels way more ziggy.

Proposal

Thus, i propose introduction of a new keyword named linkname which is valid whereever linksection is valid which changes the way a function symbol is emitted internally:

// import
pub extern fn createWindow(…) linkname("SDL_CreateWindow") …;

// export
pub export fn createWindow(…) linkname("SDL_CreateWindow") … { }

Use Case

Ashet OS

Ashet OS uses dynamic linking as the primary kernel interface, and i keep my symbols nicely namespaced and grouped:

ashet.kernel.process.debug.write_log

which sadly leads to Zig code looking likes this:

pub extern fn @"ashet.kernel.process.debug.write_log"(…) void;

which doesn't really read well, and renaming all symbols manually is tedious and error prone

C Library Wrappers

Using wrappers in Zig is common and having a simple wrapper that would export SDL functions without SDL_ prefix would make the code much nicer to read:

- const window = sdl.SDL_CreateWindow(…);
+ const window = sdl.CreateWindow(…);

apigen

apigen will gain support for something like global_prefix SDL_ which adds this prefix to all exported/imported symbols.

This would allow making nice generated Zig "Headers" which do not expose this prefix on the API surface in Zig, making the usage and the reading/writing way more convenient.

ikskuh avatar May 19 '24 09:05 ikskuh