4

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 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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);

3 Comments

I'm getting: error: root struct of file 'Build' has no member named 'Pkg' const pkg_postgres = std.build.Pkg{
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

Comments

0

In zig 0.14.*:

const my_module = b.addModule("my_module", .{
    .root_source_file = b.path("src/modules/my_module.zig"),
});

exe.root_module.addImport("my_module", my_module);

Comments

-1

zig 0.12.0-dev.817+54e7f58fc:

const foo = b.createModule(.{.source_file = .{.path = "../foo/src/main.zig"}});
exe.addModule("foo", foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.