Project import structure for base types

I have this folder / file structure:

src
    base
        color.zig
    imaging
         bmp.zig

I am a beginner, so now inside bmp.zig I have:

const color = @import("../base/color.zig");
const Bgra = color.Bgra; // line 2

which works, but is far from ideal.
So 2 questions:

  1. How can I avoid using these relative paths?
  2. Is it possible to omit this line 2? I use Bgra all over my project and would like to be able to use that one (and other base/common types) without having to explicitely refer to them in each file.
    There are off course more (Rect, Point etc. etc.)

If possible without a build.zig, because that one is future work for me.

Not an expert, but I think you can set import paths in the build.zig

From the ziglang github:

const DevEnv = @import("src/dev.zig").Env;

So, the line 2 is not necessary.

this should be how you add paths in your build.zig

exe.addIncludePath(...)

You can create a color private module in your build.zig using createModule.

    b.createModule("color", .{
        .root_source_file = b.path("src/base/color.zig"),
    });

The usage of the module is:

const color = @import("color");
const Bgra = color.Bgra;

You cannot do that. It used to work with usingnamespace.
See: make usingnamespace not put identifiers in scope and Remove usingnamespace.

The best way is to organize everything like std.
Add all the needed types in a file (e.g. src/my.zig) and expose it as a module (e.g. my).
In build.zig:

    b.createModule("my", .{
        .root_source_file = b.path("src/my.zig");
    });

In src/my.zig:

const color = @import("src/base/color.zig");
pub const Bgra = color.Bgra;
// also add `pub const` for Rect, Point, etc.

Then use it:

const my = @import("my");
const Rect = my.Rect;
// or use it directly as: my.Bgra or my.Point

This way is much better than root namespace pollution.

1 Like

Ok thanks I will create a build.zig and check out if that works.
One more question: I added once an emty build.zig and then it formats my code on save, while this option was off in the ‘Zig Language’ extension in vscode.

Is there a way to avoid that?
(I am firmly against asymmetrical formatting of braces)

The vscode setting is "editor.formatOnSave".
To override it for zig, your settings.json must be like:

    "editor.formatOnSave": true,
    "[zig]": {
        "editor.formatOnSave": false,
        "files.eol": "\n"
    }