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?
5 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
Comments
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);
3 Comments
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