#How to reach root module, from a sub module?

1 messages · Page 1 of 1 (latest)

wind galleon
#

LSP suggest const root = @import("root"); should work, but compiler disagrees, with following error, when trying to run tests:
error: root source file struct 'test_runner' has no member named ...
What am I doing wrong?

valid roost
#

tests have no control over the root source file, root refers to the test runner

wind galleon
#

oh so I can not use that in any code, that is tested?

valid roost
#

what exactly are you trying to do

wind galleon
#

I have few types defined in root.zig, and I am trying to access them from sub modules.

#

For example a common error type, that I want to use everywhere.

valid roost
#

you need to add the module as a dependency for your submodules, because the "depends on" relationship of modules works in one direction; the root module will always be the root source file of the executable/object currently being compiled

wind galleon
#

How do I do that? build.zig

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const mod = b.addModule("sgdb_zig", .{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
    });

    const exe = b.addExecutable(.{
        .name = "sgdb_zig",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{ .name = "sgdb_zig", .module = mod },
            },
        }),
    });

    b.installArtifact(exe);

    const run_step = b.step("run", "Run the app");

    const run_cmd = b.addRunArtifact(exe);
    run_step.dependOn(&run_cmd.step);

    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const mod_tests = b.addTest(.{
        .root_module = mod,
    });
    b.installArtifact(mod_tests);

    const run_mod_tests = b.addRunArtifact(mod_tests);

    const exe_tests = b.addTest(.{
        .root_module = exe.root_module,
    });

    const run_exe_tests = b.addRunArtifact(exe_tests);

    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&run_mod_tests.step);
    test_step.dependOn(&run_exe_tests.step);


    const dbg_test_step = b.step("dbg_test", "Debug tests");
    dbg_test_step.dependOn(&run_mod_tests.step);
}
valid roost
#

your sgdb_zig library has no submodules

wind galleon
#

Oh, how is the import thing called then?
in root.zig:
pub const serde = @import("utilities/serialize.zig");
in which I want to do:
const root = @import("root");

valid roost
#

within a module all paths are relative, so just ../root.zig

wind galleon
#

🤔 that works, but what the language server pretended it was correct?
And I did think, that ../ is not allowed at all.