nektro / zigquestions

A Zig community to ask for help for any experience level. Open an issue to get started :)
50 stars 0 forks source link

order of calling extern function affects linking? #29

Open expikr opened 5 months ago

expikr commented 5 months ago

This does not work:

const std = @import("std");
const win = std.os.windows;
const WINAPI = win.WINAPI;

pub fn main() void {
    //_ = MessageBoxA(null, "world!", "Hello", 0);
    _ = @extern(
        *const fn(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32, 
        .{.name="MessageBoxA", .library_name="user32"}
    )(null, "world!", "Hello", 0);
}

// extern "user32" fn MessageBoxA(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32;
LLD Link... error(link): DLL import library for -l    ╕Φ not found
error: DllImportLibraryNotFound

However, calling the commented function before the @extern symbol works

const std = @import("std");
const win = std.os.windows;
const WINAPI = win.WINAPI;

pub fn main() void {
    _ = MessageBoxA(null, "world!", "Hello", 0);
    _ = @extern(
        *const fn(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32, 
        .{.name="MessageBoxA", .library_name="user32"}
    )(null, "world!", "Hello", 0);
}

extern "user32" fn MessageBoxA(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32;

But if you swap their order, it doesn't work again:

const std = @import("std");
const win = std.os.windows;
const WINAPI = win.WINAPI;

pub fn main() void {
    _ = @extern(
        *const fn(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32, 
        .{.name="MessageBoxA", .library_name="user32"}
    )(null, "world!", "Hello", 0);
    _ = MessageBoxA(null, "world!", "Hello", 0);
}

extern "user32" fn MessageBoxA(?win.HWND, [*:0]const u8, [*:0]const u8, u32) callconv(win.WINAPI) i32;
LLD Link... error(link): DLL import library for -l    Xv not found
error: DllImportLibraryNotFound
nektro commented 5 months ago

given error(link): DLL import library for -l ╕Φ not found and error(link): DLL import library for -l Xv not found it looks like there's some memory corruption going on with regards to the .library_name argument to @export.