Importing issues, import from other directory

This is the struccture of my project created with zig init-lib, thought might learn some basics by creating a library but some complications are arising.

.
├── build.zig
├── README.md
└── src
    ├── helpers
    │   └── helper1.zig
    ├── main.zig
    ├── utils
    │   ├── datetime
    │   │   └── datetime.zig
    │   └── location
    └── helper1.zig

Now in datetime.zig I want to import a helper function from helper1.zig (both helper1.zig files are same, I was just seeing which is working, both are not working)

when I do const random = @import("./helper1.zig"); in datetime.zig:

I get this error

error: unable to load 'src/utils/datetime/helper1.zig': FileNotFound

but when I do const random = @import("../../helper1.zig"); or const random = @import("../helper1.zig"); in datetime.zig:

I get this error

error: import of file outside package path: '../helper1.zig'

Again, searched google but the things Im seeing are not related, and do I really need to modify build.zig? since everything is in the src directory only, why are relative or absolute paths not working?

1 Like

Try

const helper = @import("/helpers/helper1.zig");

to import one in src/

or

const helper = @import("/helper1.zig");

for one outside src/

❯ tree .
.
├── build.zig
└── src
    ├── helpers
    │   └── helper1.zig
    ├── main.zig
    └── utils
        └── datetime
            └── datetime.zig

❯ cat src/helpers/helper1.zig
pub fn add(a: u8, b: u8) u8 {
    return a +% b;
}

❯ cat src/utils/datetime/datetime.zig
const add = @import("../../helpers/helper1.zig").add;

pub fn thenOne(a: u8, b: u8) u8 {
    return add(a, b) +% 1;
}

❯ cat src/main.zig
const std = @import("std");

const thenOne = @import("utils/datetime/datetime.zig").thenOne;

pub fn main() !void {
    std.debug.print("{}\n", .{thenOne(1, 2)});
}

❯ zig build run
4

Double check your imports. It should work. Zig version 0.11.0

1 Like

You had helpers missing in your import path. It should have been const random = @import("../../helpers/helper1.zig");, but you were using const random = @import("../../helper1.zig");, where the folder helpers, where your helper1.zig is located is missing in the import string.

@dude_the_builder provided you with some steps to follow that elucidate this further. I just wanted to show you where the error was. Sometimes, it is hard to catch. Specially if you are a beginner.

I hope this helps.

Take a second look. There is another helper1.zig down the tree.

I think he will need to provide the command used to build or run, I bet it has something to do with the root source dir. Alas this is a bit too late now, it has been a week since he posted