Pass build option to a dependency?

Ok, I tried to reduce this by makind two small zig projects, mylib which has in its build.zig:

    const sub = b.option(bool, "sub", "Use sub, not add.") orelse false;
    const options = b.addOptions();
    options.addOption(bool, "sub", sub);

    const op_mod = b.addModule("op", .{
        .root_source_file = .{ .path = "src/op.zig" },
    });
    op_mod.addOptions("options", options);

This makes mylib either use add or sub as an operation.

Then myapp has in its build.zig:

    const mylib = b.dependency("mylib", .{});
    _ = mylib.builder.addUserInputOption("sub", "true") catch unreachable;

With or without the addUserInputOption line, the result is the same, mylib is built as if -Dsub is never passed. I also tried addUserInputFlag given this is just a bool flag, but same result.

Edit: I have a test in mylib that proves the option is working when building mylib directly.

test "Test the option" {
    if (options.sub)
        try std.testing.expect(op(3, 7) == -4)
    else
        try std.testing.expect(op(3, 7) == 10);
}

Here’s the sample:
depopt.tgz (2.3 KB)

2 Likes