Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import zig package from another zig package

Tags:

zig

I can import an package in my executable with exe.addPackagePath("name", "path") and usae it with const name = @import("name");. Now I want to include the package in another package, but I don´t understand how. Can I create an object for the package to set addPackagePath() on?

like image 551
B_old Avatar asked Oct 24 '25 15:10

B_old


2 Answers

This has changed very recently (I'm on v0.11.0-dev.1929+4ea2f441d), packages are now modules, and the way to add them is like so:

Imagine you had a file structure like so:

/src/main.zig
/src/foobar/foobar.zig

And in foobar.zig you had

// src/foobar/foobar.zig

pub fn foo()[*:0] const u8 {
   return "bar";
}

add it to your build.zig as so:

const foobar_module = b.createModule(.{
    .source_file = .{ .path = "src/foobar/foobar.zig"},
    .dependencies = &.{},
});

exe.addModule("foobar", foobar_module);

and then in src/main.zig

const std = @import("std");
const game = @import("game");


pub fn main() !void {
    // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
    std.debug.print("Foobar: {s}\n", .{foobar.foo()});
}

should print after zig build and running the executable:

Foobar: bar

See https://devlog.hexops.com/2023/zig-0-11-breaking-build-changes/#modules for more

like image 166
Bjorn Avatar answered Oct 28 '25 02:10

Bjorn


In zig 0.11.0-dev.2317+46b2f1f70:

b.addModule(.{
    .name = package_name,
    .source_file = .{ .path = package_path },
});
  • Example from https://github.com/zig-postgres/zig-postgres/blob/005fb0b27f2d658224a3c39b6e4536668d8ed9f6/build.zig#L25
  • More info https://devlog.hexops.com/2023/zig-0-11-breaking-build-changes/

In zig 0.11.0-dev.1503+17404f8e6:

const pkg_postgres = std.build.Pkg{
    .name = "postgres",
    .source = std.build.FileSource{
        .path = "deps/zig-postgres/src/postgres.zig",
    },
};
...
exe.addPackage(pkg_postgres);
  • https://zenn.dev/ousttrue/books/b2ec4e93bdc5c4/viewer/4a67f3#pkg.path
  • https://github.com/capy-ui/capy/blob/ab6d8df7123f27ae814003a31c5fda6eb6c2acd0/build_capy.zig#L25
like image 32
rofrol Avatar answered Oct 28 '25 04:10

rofrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!