Custom build file - chung-leong/zigar GitHub Wiki
Zigar uses its built-in build.zig
when compiling your Zig files. There are occasions when you
might to customize the build settings. For instance, when you're employing third-party packages.
Copy and paste the following code into a build.zig
in the same directory as your Zig module
(potentially alongside a build.zig.zon
) and make the necessary changes:
const std = @import("std");
const cfg = @import("./build-cfg.zig");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const lib = b.addSharedLibrary(.{
.name = cfg.module_name,
.root_source_file = .{ .cwd_relative = cfg.stub_path },
.target = target,
.optimize = optimize,
});
const imports = .{};
const mod = b.createModule(.{
.root_source_file = .{ .cwd_relative = cfg.module_path },
.imports = &imports,
});
mod.addIncludePath(.{ .cwd_relative = cfg.module_dir });
lib.root_module.addImport("module", mod);
if (cfg.is_wasm) {
// WASM needs to be compiled as exe
lib.kind = .exe;
lib.linkage = .static;
lib.entry = .disabled;
lib.rdynamic = true;
lib.wasi_exec_model = .reactor;
}
if (cfg.use_libc) {
lib.linkLibC();
}
const wf = switch (@hasDecl(std.Build, "addUpdateSourceFiles")) {
true => b.addUpdateSourceFiles(),
false => b.addWriteFiles(),
};
wf.addCopyFileToSource(lib.getEmittedBin(), cfg.output_path);
wf.step.dependOn(&lib.step);
b.getInstallStep().dependOn(&wf.step);
}
Adding a package
Place dependent packages in the imports
tuple. Example:
const ziglua = b.dependency("ziglua", .{
.target = target,
.optimize = optimize,
});
const imports = .{
.{ .name = "ziglua", .module = ziglua.module("ziglua") },
};
Adding a C source file
Call
addIncludePath
to add directories holding expected header files. Call
addCSourceFile
to add the source file itself.
lib.addIncludePath(.{ .path = "./libx/include" });
lib.addCSourceFile(.{ .file = .{ .path = "./libx/src/main.c" }, .flags = &.{} });
Fields in build-cfg.zig
output_path
The full path to the .so, .dylib, or .dll. file being generated.
module_name
The name of the module, i.e. the name of the Zig file without the extension.
module_path
The full path to the Zig file specified in the import statement (directly or indirectly through
sourceFiles
).
module_dir
The full path to the parent directory of module_path
.
stub_path
The full path to the Zigar module entry point.
use_libc
Whether the C standard library should be linked in. Corresponds to the
useLibc
configuration option. Relevant only for compilation to WASM.
Always true
for node-zigar.
is_wasm
Whether the target archecture is WebAssembly.