9

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.

Dave Mason
  • 669
  • 6
  • 15

2 Answers2

8

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

Dave Mason
  • 669
  • 6
  • 15
  • Is the extension mandatory or good practice? Without extension, it would feel more "package-style" than file. – Sandburg Feb 06 '23 at 10:26
3

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.

Dave Mason
  • 669
  • 6
  • 15