My first zig.build file - run raylib examples on a Mac

Here is my first zig.build file :slight_smile:
I installed raylib on a Mac using homebrew and I wanted to create a new folder, throw some example raylib code, build and run it. Using the zig as a toolchain was not as difficult as I thought!
The repository is available on github
The code is

const std = @import("std");

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

    const module = b.addModule("main", .{
        .target = target,
        .optimize = mode,
        .link_libc = true,
    });

    module.addCSourceFile(.{
        .file = b.path("src/main.c"),
        .flags = &[_][]const u8{"-std=c11"},
    });

    const exe = b.addExecutable(.{
        .name = "game",
        .root_module = module,
    });

    exe.linkSystemLibrary("raylib");

    if (target.result.os.tag == .macos) {
        exe.linkFramework("IOKit");
        exe.linkFramework("Cocoa");
        exe.linkFramework("OpenGL");
    }

    b.installArtifact(exe);
    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run the game");
    run_step.dependOn(&run_cmd.step);
}

I used this Cmake file as the source to translate from.

cmake_minimum_required(VERSION 3.15)
# the name of the executable will be game
project(game)
# Requires at least version 3.0
find_package(raylib 5.5 REQUIRED) 
# Requires C11 standard
set(CMAKE_C_STANDARD 11) 
# src/main.c is the source file
add_executable(${PROJECT_NAME} src/main.c)

target_link_libraries(${PROJECT_NAME} raylib)

# Checks if OSX and links appropriate frameworks (only required on MacOS)
if (APPLE)
    target_link_libraries(${PROJECT_NAME} "-framework IOKit")
    target_link_libraries(${PROJECT_NAME} "-framework Cocoa")
    target_link_libraries(${PROJECT_NAME} "-framework OpenGL")
endif()

I was really surprised that it worked - I know very little about zig and even less about zig.build. Any suggestions / links to articles are welcome.

5 Likes

little out of date but still useful Build System Tricks

2 Likes

Thanks a lot!