2

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?

B_old
  • 1,141
  • 3
  • 12
  • 26

3 Answers3

1

Instead of using addPackagePath, create Pkg structs directly (this way you will be able to specify sub-depencencies), and then use addPackage.

Here's an usage example of Pkg:
https://github.com/zig-community/Zig-Showdown/blob/main/build.zig#L6-L62

And here's how the structs are added to the executable:
https://github.com/zig-community/Zig-Showdown/blob/main/build.zig#L112-L118

kristoff
  • 456
  • 2
  • 3
1

In zig 0.11.0-dev.2317+46b2f1f70:

b.addModule(.{
    .name = package_name,
    .source_file = .{ .path = package_path },
});

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);
rofrol
  • 14,438
  • 7
  • 79
  • 77
  • I'm getting: error: root struct of file 'Build' has no member named 'Pkg' const pkg_postgres = std.build.Pkg{ – GLJeff Mar 28 '23 at 23:54
  • Have you seen this https://devlog.hexops.com/2023/zig-0-11-breaking-build-changes/? – rofrol Mar 30 '23 at 08:50
  • You can see working example here https://github.com/zig-postgres/zig-postgres/blob/main/build.zig – rofrol Mar 30 '23 at 08:53
1

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

Bjorn
  • 69,215
  • 39
  • 136
  • 164