Dave Mason
Dave Mason

Reputation: 871

How do I include one .zig file from another .zig file

Just exploring Zig... I have one .zig file with a bunch of comptime functions and constants, and I want to use those in other .zig programs. Equivalent to #include "my.h" in C.

Upvotes: 14

Views: 8627

Answers (3)

Jirafey
Jirafey

Reputation: 69

If you wanna import a specific function:

pub const foo = @import("foo.zig").foo;

If you wanna import a specific .zig file:

pub const foo = @import("foo.zig");

Upvotes: 0

Dave Mason
Dave Mason

Reputation: 871

You actually can use:

const bar = struct {
    usingnamespace @import("foo.zig");
};

to import a complete namespace into a struct, but not at the top level.

Upvotes: 5

Dave Mason
Dave Mason

Reputation: 871

The answer is that @import("foo.zig") almost does this. If you had foo.zig:

const a = 1;
pub const b = 2;
pub const c = 3;

then in main.zig:

const stdout = @import("std").io.getStdOut().writer();
const foo = @import("foo.zig");
const c = foo.c;
const a = foo.a;
test "@import" {
//  try stdout.print("a={}\n",.{foo.a});
//  try stdout.print("a={}\n",.{a});
    try stdout.print("b={}\n",.{foo.b});
    try stdout.print("c={}\n",.{c});
}

will print the values of b and c but if you uncomment the commented lines, you'll get an error because a wasn't exported (pub). Interestingly the const a=foo.a doesn't give an error unless a is used.

It appears that there is no way to dump all of an import into the current namespace, so if you want the names unqualified, you have to have a const line for each.

Thanks to people in the Zig discord, particularly @rimuspp and @kristoff

Upvotes: 15

Related Questions