From 4c94aebc0d243461a6221c422d475b3c693c9222 Mon Sep 17 00:00:00 2001 From: Gerhard de Clercq <11624490+Gerharddc@users.noreply.github.com> Date: Sat, 16 May 2026 20:31:12 +0000 Subject: [PATCH] Migrate Zig example to translate-c --- README.md | 23 ++++++++++++++++++----- build.zig | 9 +++++++++ src/example.zig | 4 +--- src/sdl3.h | 1 + 4 files changed, 29 insertions(+), 8 deletions(-) create mode 100644 src/sdl3.h diff --git a/README.md b/README.md index d16d31ed..ac6fc3aa 100644 --- a/README.md +++ b/README.md @@ -19,21 +19,34 @@ You can add SDL3 to your project like this by updating `build.zig.zon` from the zig fetch --save ``` -And then you can add it to your `build.zig` like this: +You'll then want to create a C header file, say `src/sdl3.h` like: +```c +#include +``` + +Next you can add the following to your `build.zig` file: ```zig const sdl = b.dependency("sdl", .{ .optimize = optimize, .target = target, }); -exe.root_module.linkLibrary(sdl.artifact("SDL3")); +const sdl3_lib = sdl.artifact("SDL3"); + +const sdl3_h = b.addTranslateC(.{ + .root_source_file = b.path("src/sdl3.h"), + .target = target, + .optimize = optimize, +}); +sdl3_h.addSystemIncludePath(sdl3_lib.getEmittedIncludeTree()); + +exe.root_module.linkLibrary(sdl3_lib); +exe.root_module.addImport("sdl3_h", sdl3_h.createModule()); ``` Finally, you can use SDL's C API from Zig like this: ```zig const std = @import("std"); -const c = @cImport({ - @cInclude("SDL3/SDL.h"); -}); +const c = @import("sdl3_h"); if (!c.SDL_Init(c.SDL_INIT_VIDEO)) { std.debug.panic("SDL_Init failed: {s}\n", .{c.SDL_GetError()}); } diff --git a/build.zig b/build.zig index 05437873..d105bfa6 100644 --- a/build.zig +++ b/build.zig @@ -116,6 +116,14 @@ pub fn build(b: *std.Build) !void { // Add the Wayland scanner step linux.addWaylandScannerStep(b); + // Translate the C header for the example + const sdl3_h = b.addTranslateC(.{ + .root_source_file = b.path("src/sdl3.h"), + .target = target, + .optimize = optimize, + }); + sdl3_h.addSystemIncludePath(lib.getEmittedIncludeTree()); + // Add the example const example = b.addExecutable(.{ .name = "example", @@ -126,6 +134,7 @@ pub fn build(b: *std.Build) !void { }), }); example.root_module.linkLibrary(lib); + example.root_module.addImport("sdl3_h", sdl3_h.createModule()); const build_example_step = b.step("example", "Build the example app"); build_example_step.dependOn(&example.step); diff --git a/src/example.zig b/src/example.zig index 80444525..e2a96176 100644 --- a/src/example.zig +++ b/src/example.zig @@ -1,7 +1,5 @@ const std = @import("std"); -const c = @cImport({ - @cInclude("SDL3/SDL.h"); -}); +const c = @import("sdl3_h"); const Io = std.Io; diff --git a/src/sdl3.h b/src/sdl3.h new file mode 100644 index 00000000..ba66a343 --- /dev/null +++ b/src/sdl3.h @@ -0,0 +1 @@ +#include