I’m on Linux (OS: Xubuntu 22.04.3 LTS x86_64, Kernel: 5.15.0-86-generic) and I am trying to cross compile a Node.js addon for Windows / macOS.
This Node.js addon uses the Node-API, a C API whose header files I need to include when building the addon. I keep these header files in the deps
directory of my project. The compiled artifact is a shared library.
I created a repo with a minimal reproducible example: GitHub - jackdbd/zig-nodeapi-example
Compiling for Linux
I’m able to compile for Linux either using this command…
zig build-lib -ODebug -dynamic -lc \
-isystem ./deps/node-v18.17.0/include/node \
-femit-bin=dist/debug/addon.node \
src/addon.zig
…or using this build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const name = "addon";
const lib = b.addSharedLibrary(.{
.name = name,
.root_source_file = .{ .path = "src" ++ std.fs.path.sep_str ++ name ++ ".zig" },
.link_libc = true,
.target = target,
.optimize = optimize,
});
lib.addSystemIncludePath(.{ .path = "deps/node-v18.17.0/include/node" });
b.installArtifact(lib);
}
Cross-compiling for Windows
I am now trying to cross-compile for Windows using this command…
zig build-lib -ODebug -dynamic -lc \
-isystem ./deps/node-v18.17.0/include/node \
-target x86_64-windows-gnu \
src/addon.zig
…but I am getting many linker errors like this one:
error: lld-link: undefined symbol: napi_create_function
note: referenced by /home/jack/repos/zig-nodeapi-example/src/napi.zig:30
note: addon.dll.obj:(napi.register_function__anon_3460)
note: referenced by /home/jack/repos/zig-nodeapi-example/src/napi.zig:30
note: addon.dll.obj:(napi.register_function__anon_3468)
Note: the function napi_create_function
is defined in js_native_api.h
, which is a header file included by napi_api.h
.
Cross-compiling for macOS
I also tried to cross-compile for macOS using -target aarch-macos-none
and -target x86_64-macos-none
. That also didn’t work, and MachO gives me errors like this one:
error: undefined reference to symbol _napi_get_value_string_utf8
note: referenced in dist/debug/addon.node.o
Why am I getting these linker errors? Isn’t enough to add -isystem
when using zig build-lib
, or calling lib.addSystemIncludePath()
when using build.zig
? I also tried to add --verbose-link
but can’t really understand what the issue is.