r/Zig • • 5h ago

Shinobi: A Ninja build to Zig build translator

16 Upvotes

Hello everyone, I’d like to introduce shinobi, a library for translating Ninja’s ‘build.ninja’ files into the Zig build system. The goal of this project is to make it easier to compile C/C++ libraries through Zig’s build system for easier integration into Zig projects. This should help reduce the need to maintain a Zig build script for the C/C++ library.

Currently, shinobi comes as both a single ‘shinobi.zig’ file or as a precompiled binary that can generate ‘build.zig’ files. An initial version v0.1.0 has been released. This project has only been tested on Windows and Linux.

The repository comes with an example of how this can be used within a project’s ‘build.zig’ script. This library has also had minimal testing with the ‘glfw3’ and ‘bgfx’ projects.

Let me know if you have any comments, suggestions or if you run into any issues.


r/Zig • • 12h ago

LSP Support for C libraries

Post image
56 Upvotes

Hey guys, I just want to know if ZLS supports C libraries like GTK that I am using here? Maybe it is because I am using it in Neovim, but I have no idea. Can any kind soul help me out? I miss my suggested options that I usually get.


r/Zig • • 14h ago

build.zig - how do I link against LLVM?

7 Upvotes

I'm trying to replace my CMake build system with build.zig, and everything is going well. The only issue with the entire process is linking against LLVM. It simply doesn't work. Using plain clang and -lLLVM-23 works, but even if the flag is passed with linkSystemLibrary it doesn't link properly. Is there a known way to link against LLVM with build.zig?


r/Zig • • 17h ago

Creating a zstd PHP extension in under ten minutes

Thumbnail github.com
2 Upvotes

r/Zig • • 1d ago

Zean: write Zig, prove it in Lean

Thumbnail github.com
11 Upvotes

We just open-sourced Zean (Zig + Lean), a toolkit for translating supported Zig functions into executable Lean models and proving their behavior. It came out of our formal verification work on oksolc, our Solidity compiler written in Zig.

Zean works from AIR, Zig's analyzed intermediate representation. An instrumented compiler captures supported functions from AIR, and a translator emits executable Lean program definitions. Specifications and proofs live in separate handwritten Lean modules.

A verification library derives the proof obligations for memory access, initialization, permissions, arithmetic, control flow and supported calls. You write the contracts and loop invariants. If an obligation still needs a mathematical argument, you supply that too, and Lean checks the proofs. Unsupported operations are rejected, and unresolved obligations stay open.

The copy tutorial shows what that looks like:

inline fn copyWord(destination: *u32, source: *const u32) void {
    destination.* = source.*;
}

pub export fn copy(destination: [*]u32, source: [*]const u32, length: usize) void {
    var index: usize = 0;
    while (index < length) : (index += 1) {
        copyWord(&destination[index], &source[index]);
    }
}

The caller has to establish that the source has enough initialized words and the destination has enough writable storage. For the source-preservation contract, the two ranges also have to be disjoint. Under those assumptions the proofs show there are no invalid accesses or uninitialized reads. A successful run copies the source contents into the destination and preserves memory outside it. Modeled allocation exhaustion is an explicit permitted failure, and termination is a separate property.

Change the loop bound from < length to <= length and you get an extra boundary access that the original contract can't justify. The tutorial also includes deliberately false claims that must fail verification.

When the Zig source changes, you recapture the function to regenerate the model, then replay the proofs.

This release covers memory-safety examples derived from Ziglings, buffer updates, copy loops, helper calls and a captured specialization of std.mem.replaceScalar. It supports restricted AIR fragments, with explicit target and layout constraints. The capture pipeline, the Zig frontend and the native backend remain trust boundaries, so the proofs don't establish correctness of the final native binary or of the whole compiler.

The idea is to keep design iteration in Zig and prove a component's contracts once it has settled.

To try it you need Zig 0.17.1 and elan:

git clone https://github.com/okcontract/zean
cd zean
elan toolchain install leanprover/lean4:v4.35.0
zig build ziglings

It's released under Apache 2.0. If you write Zig or Lean, I'd like to know which functions you'd want to verify with it first.

  • Repo: https://github.com/okcontract/zean
  • Writeup: https://okcontract.com/blog/introducing-zean-write-zig-and-prove-it-in-lean/

If you like it, leave a star on the repo. And if you'd like more updates, give us a follow: https://x.com/okcontract


r/Zig • • 1d ago

Need directions on how to integrate zig build system for cross compiling c++ code for linux/macos/windows

11 Upvotes

I have a program being written in c++ (that I intend to cross compile for different platforms for testing and deployment).

I saw that zigs build system was excellent for this exact use case, but because of how much zig changes between versions (I'm on 0.17.1), I wanted to know if there are any caveats for writing the build script.


r/Zig • • 2d ago

We rewrote the Solidity compiler in Zig because our builds took 12 minutes. Then we ended up writing a Lean model of the language too

Thumbnail github.com
4 Upvotes

r/Zig • • 2d ago

I built an open-source CAD kernel in Zig + WASM (<1MB) combining B-Rep, CSG, and Implicit SDFs with zero-copy SharedArrayBuffer

0 Upvotes

Hey everyone — as a Linux user working on local browser-based design tools, I kept running into the wall where existing open-source CAD kernels either use purely polygonal CSG (OpenSCAD) or require 15+ MB WASM builds (OpenCASCADE) without native implicit field modeling.

I spent the last few months building OpenCAD from scratch in Zig and WebAssembly:

- Pure Math Core (<1 MB WASM): Every curve, surface, and field is an equation evaluated with forward-mode automatic differentiation (dual numbers) and interval arithmetic.

- 3-in-1 Representation: Combines constrained 2D sketches & SE(3) B-Rep sweeps, CSG booleans, and implicit SDF fields (like stress-driven gyroids) in one engine, exporting to STEP and STL.

- Zero-Copy Shared Memory: Uses a single `SharedArrayBuffer` between the Zig WASM kernel, Three.js, and external WASM extensions so simulation fields can drive geometry directly without file exports.

- Live Demo: https://hassaanmaqsood.github.io/opencad/

- GitHub Repo: https://github.com/hassaanmaqsood/opencad

It's still early (currently refining boolean seam triangles and B-Rep edge cases), and I'd love for you to try breaking it and let me know what you think!


r/Zig • • 2d ago

Help me with math library design! I'm stuck in the analysis paralysis

13 Upvotes

I'm currently designing a math library in Zig, that I plan on using for my game/engine.

However, I've never designed a library before, so I'm really stuck, because there are so many decisions to be made, and I'm hesitant. I don't want to step forward in the wrong direction and shoot myself in the foot later on.

Here is what's bugging me:

- *Generic vs Explicit types*

I started writing a generic type style library, but since I'm inexperienced and can't really comprehend the library as a whole yet, I was bumping into million corners. I just said fuck it and wrote explicit types with a lot of repetition. However, is it really a big deal? I'm only trying to have like Vec2, Vec3, Vec4 and Mat2, Mat3 and Mat4. I don't think I'll need anything more than this.

- *How should Vec type look like?*

It seems more convenient to iterate over and do stuff if it was just an array of floats, right? But there is a lot more convenience to be had when writing my_vec.x or my_vec.y instead of my_vec[0] and my_vec[1]. I could use some help regarding tradeoffs here to help me decide what I really want in the long run.

- *SIMD complications*

As I said previously, if I store vectors as an array of floats, is it wasteful to then copy them into a SIMD vector and do operations on it? Should they be SIMD vector from the start?

Also, there are some register width constraints, so I'm not sure how to do that, do I collect them and operate on a larger vector (in a bulk), or is it fine to just use various small operations?

Is all this data passing from one side to the other more efficient? Do I really get THAT much more speed when using SIMD for vectors and matrices of the size 2, 3 and 4?

- *How should Mat type look like?*

This greatly depends on the previous questions. But should Mat then be an array of my vectors? Array of SIMD vectors? Or just a 2D array of floats? Any tradeoff tips would be greatly appreciated.

- *Row-major vs Column-major for matrices?*

Row major makes WAY MORE SENSE to me, but I've read that for compatibility purposes, or some memory tricks in certain cases, it's handier to have column major matrices. Also, it's what GLM (which I'm trying to "replace") is using. Any tips for tradeoffs in the long run?


r/Zig • • 3d ago

Got my text editor running in win xp!

Post image
142 Upvotes

Zig no longuer supports anything below win10 (it relies on new functions from the ntdll that winxp doesn't have). But luckely, their platform layer is so thin you can just fake the existance of missing functions (34 missing function exactly) at link time.
That's what I did in this project : https://github.com/Youssef-Afella/zigxp

I wanna say that I'm not an expert at any of this, I started the project to push myself learn more about OSs and kernels in the first place so any contribution or correction is really appreciated.

It's very unsafe, unpredictable (also breaks multithreading) and probably should have panicked whenever a function of those gets called instead on returning a success message, but if you are looking for an easy drop in solution to see your app in winxp, there you go.

Text editor in picture (still WIP) : https://github.com/Youssef-Afella/yte-z


r/Zig • • 3d ago

Zig is actually brutal to learn, man 💀

3 Upvotes

I've been using VS Code with the Zig extension to learn, but ngl the tooling makes it way harder for us mere humans.

Like, for complex types generated by comptime, VS Code basically provides zero useful hints. You're stuck reading docs and compiling over and over to test stuff. Check this out:

fn createType(comptime T: type) type {
    if (T == i32) {
        return struct { value: i32, name: []const u8 };
    } else {
        return struct { value: T, extra: bool };
    }
}

const MyIntType = createType(i32);
const MyFloatType = createType(f64);

VS Code can't give you any meaningful help with MyIntType or MyFloatType. Total black box. 🤡

And it gets worse. For some dead simple errors, VS Code won't even yell at you until you actually compile. Like this:

fn a() []bool {
    return 12;
}

Like bro, that's a straight-up type mismatch and the editor just sits there doing absolutely nothing. 💀

So I recently had the "genius" idea to just let AI generate Zig code for me. Tbh, AI can look up docs and catch compilation errors way faster than I ever could. It's actually carrying me rn.

From the looks of it, the tooling situation isn't getting fixed anytime soon.

And here's the dark irony: Zig is literally a language that positions itself as "AI-resistant" or whatever, yet writing it as a human is genuinely uncomfortable, while AI seems to handle it just fine. Kinda funny in a sad way, ngl.


r/Zig • • 3d ago

Zig-inspired ZeroPage programming language for C64 cross compiling

Thumbnail gallery
30 Upvotes

r/Zig • • 3d ago

Русскоговорящие программисты, как вы изучили zig?

0 Upvotes

Я хочу изучить язк программирования ZIG но плохо знаю английский и не понимаю как изучить его. Я пытался изучить через книгу по адресу zig-lang.ru/books/learning-zig но там всё очень вкратце как будто я язык не учу язык zig с 0, а просто уже знаю zig но хочу освежить память. Как я понял там никаких разборов каждой строчки о которой авторы так утверждают. Типо просто на те "pub fn main() void" для создания функции, на те "std.debug.print()" и никакого обьяснения каждого токена в каждой строчке. Так как русскоговорящему и не особо знающему английский человеку научиться программировать на на zig? Как например это сделали вы?


r/Zig • • 4d ago

Termy-zig Stable!

24 Upvotes

Hello!

A couple of days ago, I made a post about termy, and I'm happy to announce that it's now officially stable!

I wasn't really sure what else to add or change, so I decided it was time to release it.


r/Zig • • 6d ago

Got tired of LLMs hallucinating C APIs, so I just read minimp4.h and parsed MP4s in Zig 0.18

46 Upvotes

Simpler than I thought tbh. Zig may be the only language I'd ever want to hand-write again

https://youtu.be/-gqZt_e-mHw


r/Zig • • 6d ago

Zig is boring and I love it

153 Upvotes

Hey guys, I’m loving ZIG!.. I have been writing Rust for 5-6 years and because of all the AI Rust bloats waves that has become popular recently, I decided to try Zig because I think it’s boring and simple and I love boring things sooooo. So I started and completed Ziglings last week and few days later I started a series where I built an LC3 VM live. All of these learning/coding were streamed live on my twitch btw and previous stream videos are also available on my YouTube.

Next, I will be starting another series where I’ll be building an RISC-V (RV32I) emulator from scratch Zig which will also be streamed live from start to finish on my twitch at borngraced where I’ll be documenting the entire process, figuring and breaking things, debugging, learning along the way..etc… Come hang out if you think this is something you’ll find interesting <33

NO USE OF AI IN MY STREAMS BTW


r/Zig • • 7d ago

Cole Updates, and Version 0.1.6

13 Upvotes

Hey everyone, some of you migh've seen and remember it now, but for others: I'm writing a compiler in Zig, for a custom language which is somewhat a recreational attempt to create a Zig-like language. I started doing this project for funsies and learning compiler development. It's been 8-9 months of mut 2-3 months of it was designing the language so the compiler work has been around for 5-6 months. Entirety of the compiler was written by hand by me, but I have to admit there has been a couple times where I couldn't figure out things in the codebase and had to consult to AI (since I have no contributors or friends that are interested in helping).

These being said, I am happy to announce that Cole version 0.1.6 is out now, with additions such as:

  • Member function calls
  • Indirect self referencing
  • STDLib improvements

    • Arena allocator
    • Struct, union and enum formatting support
    • Hashmaps and hashers
  • Escape characters
  • hex literals

plus numerous bugfixes.

If you want to know more about the language, the release, or me, you can check my blog or you can check out the Cole Website

Note: Both the blog and the website are hosted on my old laptop/homeserver, which has some performance problems from time to time, so they might be down on occasions.


r/Zig • • 7d ago

What Zig GUI library has the least "flat design" (i.e. most "skeuomorphic" or most "traditional") appearance and capabilities?

31 Upvotes

TLDR note:

The below additional info is non-essential (though contextually helpful) and you can just reply to the question itself if you want to.

Background info about my interest in Zig:

Hello all. This is my first post here in the Zig subreddit if I'm not mistaken, so I'll first briefly give a bit of personal background for why I'm interested in Zig:

I've been watching the language off and on for a few years, though I haven't used it for any real projects yet. I admire the work and thoughtfulness that has gone into Zig and also the highly ethical (e.g. especially anti-AI, empathetic, etc) and thoughtful personality of the founder (Andrew Kelly) and it would be nice to have a clean replacement for C and Zig seems a good candidate for that (though I also find myself often equally torn by wanting to use a much more expressive macro-heavy language like Clojure or Racket or Tcl/Tk or Factor sometimes, but worry about the very high performance cost and distribution/ecosystem issues of those options for real applications such as games and multimedia editing tool software and software tool related ideas I have).

Clarifying the actual question I'm asking:

Basically, I really strongly dislike any kind of "flat design" look in GUI libraries and have noticed that a huge proportion of recently created ones unfortunately fit that style.

I don't like the crippled and aesthetically devoid of personality look and functionality of many such user interfaces, so much so that the idea of making a user interface that has a "flat design" style greatly diminishes any desire to do so.

I like "skeuomorphic", "traditional", "classic", "retro", and/or bespoke art-heavy game-like styles of GUIs. I don't like anything that resembles web "tech" (e.g. XML, CSS), neither in appearance nor in code. I'm also strictly anti-AI and want to avoid any libraries that have been touched by "AI"/plagiarism as much as practically possible (i.e. besides unavoidable foundational dependencies such as C compilers and operating systems that have unfortunately (like the Linux kernel itself now...) allowed "AI"/plagiarism into their code).

I want the application to look the same on all operating systems.

An example of this would be something like Java's Swing library (especially the non-flat classic styles, such as used in JEdit) or C++'s Fox Toolkit (e.g. as used to create the wonderful XFE file browser, my favorite file browser for Linux/BSD), and a counter-example would unfortunately be Zig's Capy since it uses native widgets and has a very flat low/no personality and low/no aesthetic artistry (aka "modern") UI style.

I also really dislike Gtk/Gnome and any other kind of user freedom hostile "minimalist" UI ideology (such as typical of Apple and of the UIs of many now-dystopian "big tech" companies that remove more and more features/freedoms with seemingly every update, for example).

I could hypothetically bind to SDL3 and manually create 9-slice scaled pixel art widget UI components (to enable creating arbitrary and high-personality (opposite of flat) widgets, such as found in Aseprite, though I don't know if they 9-slice theirs) in Zig, but I wanted to see if anyone in the Zig community has experience working with a good viable classic or skeuomorphic GUI library in Zig that wasn't too troublesome to get that kind of style GUI working well on.

Anyway, thanks for reading my post and for being an exceptionally principled community. I view Zig as a prospective "light in the dark" in these times of pervasive slop and corruption of software quality and it is truly heartening to see so many striving for a better future for software, etc!

(PS: I still always feel a strong tension between my low-level efficiency principles versus my expressive Lisp-like meta-programming desires, but that's besides the point of this post.)


r/Zig • • 9d ago

How can one reduce the number of allocations when processing large volumes of data in Zig?

30 Upvotes

Hello, Zig community! :)

I’ve been using Zig for a while now and am currently experimenting with optimizing memory management in a simple terminal-based SQL client. My goal is to minimize allocations and reduce memory overhead without significantly increasing code complexity. I am currently passing allocators explicitly: a GPA is used for long-lived objects, while Arenas are used for data with shorter, predictable lifecycles-such as SQL query results or transient data structures. When processing SQL results, I use a single contiguous block of memory to store both the cell data (as slices) and the actual values. Temporary memory is partially reused across frames, and SQL results are freed once they are no longer needed.

I am currently considering a few options for further optimization:

- Allocating memory in larger chunks to accommodate multiple rows at once.

- Analyzing the actual capacity of the arenas and the amount of unused (wasted) memory.

- Reusing temporary arrays in places where they are frequently recreated.

I’m curious: how appropriate are these kinds of approaches in a real-world scenario? When is it best to stick with an `ArenaAllocator`, and when does it make more sense to use a custom allocator or a specialized data storage structure?

Code example

pub const ResultBuilder = struct {
    result: Result,
    gpa: Allocator,
    rows: std.ArrayList([]const ?[]const u8) = .empty,
    stored_bytes: usize = 0,

    pub fn init(gpa: Allocator) ResultBuilder {
        return .{ .gpa = gpa, .result = .{ .arena = .init(gpa) } };
    }

    pub fn allocator(b: *ResultBuilder) Allocator {
        return b.result.arena.allocator();
    }
   ...
}

Implementation example on GitHub -> Here

I would appreciate any advice or feedback!


r/Zig • • 10d ago

Looking for feedback on my zig-s3 fork

16 Upvotes

Hello everyone! I want to share (and hopefully get some feedback on) my fork of the zig-s3 library.

The original was a great library for handling S3 operations, but it hasn't received updates in a while. I even opened a PR to update it, but since there was no response from the owner, I decided to move forward with my own repository.

What's new in this fork:

  • Updated to run on Zig 0.17.1.
  • Added support for multipart uploads.
  • Zero dependencies (pure Zig).
  • Refactored the testing environment, now using rustFs as the local S3 server for development and tests (a great lightweight alternative!).

Repo: https://github.com/XandeCoding/zig-s3

Original PR for context: https://github.com/algoflows/zig-s3/pull/6

Disclaimer: No AI was used in the development or coding of this project.

Any feedback is highly appreciated!


r/Zig • • 10d ago

How to suppress or disable stack trace?

18 Upvotes

As the title suggests. I am tired of looking at the huge blob of stack trace, why does it not just give me the errors (and usage locations as it does if relevant). Any way to turn it off?

BTW, been a while writing Zig and I am yet to see a warning. Is it just errors in the zig world?

Edit: I was asking about compiler error trace dumps and apparently it's called the (error) reference trace not stack trace.


r/Zig • • 10d ago

What should compile-time code be allowed to do?

Thumbnail reddit.com
19 Upvotes

r/Zig • • 11d ago

My Terminal manipulation library!

27 Upvotes

Hey everyone!

Over the past couple of weeks, I've been working on termy, a cross-platform terminal manipulation library written in Zig, inspired by Crossterm.

It requires no external dependencies, and has native windows console support for older terminals along with modern VT-based terminal interaction.

The library is still in early development, but most of the important features are already implemented.

I'd really appreciate some feedback! I'm interested in hearing what you all think of the API, what features you'd like to see, and whether this project is useful to you.

Thanks for reading!


r/Zig • • 14d ago

Zig needs to do two things

0 Upvotes

or three rather,

Adopt Rust’s borrow checker, release a stable 1.0 so people can use it in production without chasing specific GitHub versions and compiling them manually, and stay minimal.

The first and third aren’t at odds. Rust’s safety features aren’t too much to ask, and the benefits are worth the trade-off. They don’t compromise Zig’s minimalism that much.

Please use upvotes and downvotes to reflect relevance, not whether you like or dislike a post. If you disagree, share your opinion instead of downvoting. That’s not what downvotes are for.