ostanton::blog::posts::cmake_to_zig

using namespace ostanton;

CMake to Zig build

26 May 2025

Recently I had the idea to support Zig’s build system for Tails Engine. I thought it would be a fun experiment and, if I enjoyed it, would let me move away from CMake (which is great and all but it really does get old). Adding the Zig build system meant translating my existing CMakeLists into a build.zig file and a build.zig.zon file.

First things first was to get a dummy test project building, outside of the Tails Engine as a whole. In the test project I had the structure:

[root]
- include/
  - print.hpp
- src/
  - main.cpp
  - print.cpp
- build.zig
- build.zig.zon

All this does is declare a print function in print.hpp, defines it in print.cpp, and uses it in main.cpp. So with the following few lines, it was a rather easy task.

// build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimise = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "test_proj",
        .target = target,
        .optimize = optimise,
    });
    exe.addIncludePath(b.path("include"));
    exe.addCSourceFiles(.{
        .files = &.{
            "src/main.cpp",
            "src/print.cpp",
        },
    });
    exe.linkLibCpp();

    b.installArtifact(exe);
}

Adding a library is pretty much the same except you use addSharedLibrary() or addStaticLibrary() depending on the type (they all return a pointer to std.Build.Step.Compile, which is treated as an "artifact". More info on terms Zig uses here, and another helpful page about how the build system works (which seems to be a bit out of date but still helpful)).

However, immediately I had a problem. One of the gripes I have with CMake is the need to list every file you want to include in the build process. Due to me using Rider and MSVC, including headers is also necessary so they appear as typical solution files, so that’s already at least double the files listed. It’s only slightly aided by the fact that you can have a CMakeLists file in the root of each folder with code, and they’re picked up with an add_subdirectory(). This means you don’t need to write long path names out, just the files next to the current CMakeLists.txt. In Zig, however, because it doesn’t generate a solution, we don’t care about finding headers. And, because it’s just Zig code, it’s trivial to walk the entire src directory collecting .cpp files in an array. This is seriously cool stuff now.

// build.zig
var sources = std.ArrayList([]const u8).init(b.allocator);
{
    var dir = try std.fs.cwd().openDir("src/Tails", .{ .iterate = true });

    var walker = try dir.walk(b.allocator);
    defer walker.deinit();

    while (try walker.next()) |entry| {
        const ext = std.fs.path.extension(entry.basename);
        if (std.mem.eql(u8, ext, ".cpp")) {
            try sources.append(b.pathJoin(&.{ "src/Tails", entry.path }));
        }
    }
}
lib.addCSourceFiles(.{ .files = sources.items });

Compiler flags and specifying the language (C, C++, Objective-C, etc.) are also defined in the addCSourceFiles() function. I’ve set Clang to use -std=c++20 and some typical warning flags that are set in the existing CMakeLists for Tails Engine.

Just because you’ve set some flags for the library does not mean they carry over to the executable that’s linking against it! If your library uses C++20 features like concepts, your executable will fail to compile if it includes headers using those features and doesn’t also have the C++20 flag!

lib.addCSourceFiles(.{
    .files = sources.items,
    .flags = &.{ "-std=c++20" },
});

“But wait!” I hear you cry, “What about the dependencies!?”. Ah yes, the dependencies. Luckily, Tails Engine only relies on SDL3 externally. It uses stb_image too but that’s just a header in the src directory. The prospect of linking with a library like SDL, on Windows of all platforms, terrified me. However, thanks to the amazing Zig community, people have ported SDL to the Zig build system, making it as easy as adding a typical Zig dependency (the one I’m using is SDL):

// build.zig.zon
.{
    .name = .tails,
    .version = "0.0.1",
    .fingerprint = 0xea8d5f63b7dee9e,
    .dependencies = .{
        .sdl = .{
            .url = "git+https://github.com/castholm/SDL.git#0ab7c9830bf17c1a2404461a88c0fdedf95309a4",
            .hash = "sdl-0.2.3+3.2.14-7uIn9Gh6fgEdV7R2A723rZxtbgkVd0PHIs2rvshLBqgV",
        },
    },
    .paths = .{
        "build.zig",
        "build.zig.zon",
        "example/",
        "include/",
        "src/",
        "README.md",
    },
}

You can use the command zig fetch --save git+[url] to add the dependency automatically, instead of adding it manually in build.zig.zon.

// build.zig
const sdl_dep = b.dependency("sdl", .{
    .target = target,
    .optimize = optimise,
});
lib.linkLibrary(sdl_dep.artifact("SDL3"));

The dependency name is what's in build.zig.zon, and the artifact name is the library name set in SDL3's build.zig (much like how Tails Engine's is just "tails").

Amazingly, this works! Even more amazingly is how much shorter AND easier it is than CMake. I vote to ditch CMake in favour of Zig for everything.

OK, so we have a build.zig which creates a library, gathers its source files, links in SDL3, adds the include directory, what else? Oh yeah, that’s right. Macro definitions. Tails Engine uses definitions in CMake for things like enabling logging and asserts, and I wanted this to be in the Zig version too. CMake has a pretty nice way of adding options to the generation process, which you can then check in the script and add definitions based on. Zig, funnily enough, also has this, and it’s also shorter and cleaner. If you call zig build --help in the project's directory, these options also display under there with their descriptions (which is very helpful!).

// build.zig
// b.option() returns an optional, so "orelse" returns true as a default value if it is invalid
const enable_asserts = b.option(
    bool,
    "asserts",
    "Enable/disable asserts. Always disabled in release builds (default - true)",
) orelse true;
if (enable_asserts)
    // do things

The only problem then is adding the definitions themselves, which is done through the std.Build.Step.Compile’s root_module.

// build.zig
if (enable_asserts)
    lib.root_module.addCMacro("TAILS_ENABLE_ASSERTS", "");

This is all fine and dandy now, but if you were to try and use this library in some external executable, it would not work. This is because we are looking at the current working directory in our search for the source files. This acts as the executable’s current working directory when we try and link our library to it instead of the library’s directory. How do we fix this? We can get the absolute build path via b.build_root, and simply append our previously local directory to our source files. We then use std.fs.openDirAbsolute() instead of the current working directory's openDir(), and Bob’s your uncle.

// build.zig
var sources = std.ArrayList([]const u8).init(b.allocator);
{
    const tails_src = "src/Tails";
    var dir = try std.fs.openDirAbsolute(
        b.pathJoin(&.{
            b.build_root.path.?,
            tails_src,
        }),
        .{
            .iterate = true,
        },
    );

    var walker = try dir.walk(b.allocator);
    defer walker.deinit();

    while (try walker.next()) |entry| {
        const ext = std.fs.path.extension(entry.basename);
        if (std.mem.eql(u8, ext, ".cpp")) {
            try sources.append(b.pathJoin(&.{ tails_src, entry.path }));
        }
    }
}

Side note, realising why Zig was failing to find the Tails Engine sources when linking it to an external executable and then figuring out how to fix it was superbly annoying. With a language such as Zig, you have to give it some slack for with the documentation side of things, and I did have to go looking around the standard library for clues as to what could help me. It turned out to be rather obvious in the end, but it would have been nice to be in the documentation!

And with that, we have Tails Engine building with Zig! I’m really looking forward to where Zig goes in the future, and I found this whole experience rather trivial (except for the absolute directory debacle. The rest was just one evening’s worth). My only gripe with it is the lack of easily accessible and understandable documentation. I suppose Zig just isn’t mature enough for that kind of thing yet. Fair enough.

You can see the full build.zig for Tails Engine here.

::blog::tags