Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

zig

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.

like image 658
Dave Mason Avatar asked Dec 14 '25 17:12

Dave Mason


1 Answers

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

like image 151
Dave Mason Avatar answered Dec 19 '25 06:12

Dave Mason