Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How do you do modules in zig? Like when you have your code in 5 C files and link the obj? How to do that?


@import can take a path. I guess i should put that in there. The details are pretty cool, the imported file becomes a struct!


So are they all recompiled? What about compilation/linking time? Or is this not a concern since the zig compiler is fast?


Zig sources go into a single big compilation unit. C sources can be split into multiple CUs and Zig has a neat caching system that integrates with clang to only rebuild a CU when necessary (you don't have to do anything to set it up).

An incremental compilation feature is coming to the self-hosted compiler: https://kristoff.it/blog/zig-new-relationship-llvm/


C source files are only compiled on full rebuilds, or when the C source file changes, just like in regular C projects. You can distribute precompiled libraries, but I think given that one of Zigs prominent features is simple cross-compilation to all sorts of platforms, compiling from source is preferred.

The @import method is only for "importing" C headers with declarations and have them automatically converted to Zig interface declarations (so in most cases you don't need manually maintained language bindings). For compiling the associated C soure files, Zig has a builtin C compiler.


I think you misunderstood my question. I am not (in this question) interested in C or C interopability of zig, but how to structure larger zig project (how zig thinks this should be handled)


Yeah, I realized that after I hit send :)

For regular Zig source files, you just import them into other Zig source files, up to the "main file". Such imports are wrapped into a module struct (imported modules are just regular structs). The Zig build system takes care of efficiently compiling all this with proper incremental build support (one can explore the zig-cache subdirectory which is maintained by the zig compiler for details).

For example, these are the imports in a top-level file:

https://github.com/floooh/pacman.zig/blob/ed42fad79c3e9b4432...

The sokol.zig file groups other modules under a common namespace:

https://github.com/floooh/pacman.zig/blob/main/src/sokol/sok...

...which in turn imports "leaf modules" like this:

https://github.com/floooh/pacman.zig/blob/main/src/sokol/aud...

...it's one of the most straightforward module systems I've seen yet in any language.


Just like JavaScript modules, kind of.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: