Zig and SDL2

Bare bones Program

trtl is my first foray into low level systems programming. While zig seems well suited for this, I wanted to use a library that would abstract away low level graphics, audio and input functionality. After a lot of research, I zeroed down on sdl2.

Given my lack of experience in the c ecosystem, even trivial things like linking libraries took me a while to figure out. Given Zig's C interop, I wanted to avoid using any sdl wrappers for zig and figure out how to do this myself.

I was able to setup a barebones zig program which integrates sdl2. I also deliberately avoided using the zig build file to remove that complexity. Will add one as my needs evolve.

const std = @import("std"); const sdl = @cImport({ @cInclude("SDL.h"); }); pub fn main() void{ std.debug.print("hi",.{}); _ = sdl.SDL_Init(sdl.SDL_INIT_VIDEO); defer sdl.SDL_Quit(); const window = sdl.SDL_CreateWindow("trtl", sdl.SDL_WINDOWPOS_CENTERED, sdl.SDL_WINDOWPOS_CENTERED, 166, 166, 0); defer sdl.SDL_DestroyWindow(window); const surface = sdl.SDL_GetWindowSurface(window); var quit = false; while (!quit) { var event: sdl.SDL_Event = undefined; while (sdl.SDL_PollEvent(&event) != 0) { switch (event.@"type") { sdl.SDL_QUIT => { quit = true; }, else => {}, } } // Draw a white cross on red background _ = sdl.SDL_FillRect(surface, 0, 0xff0000); const v = sdl.SDL_Rect{ .x = 33, .y = 66, .w = 100, .h = 34 }; _ = sdl.SDL_FillRect(surface, &v, 0xffffff); const h = sdl.SDL_Rect{ .x = 66, .y = 33, .w = 34, .h = 100 }; _ = sdl.SDL_FillRect(surface, &h, 0xffffff); _ = sdl.SDL_UpdateWindowSurface(window); } }

Compiling Notes

  • command : zig build-exe main.zig -OReleaseSmall -fstrip $(pkg-config --libs --cflags sdl2) -lc
  • lc links libc
  • pkg-config helps get include path for sdl2
  • -fstrip parameter of build-exe omits debug symbols from the output of pkg-config

Reference

https://zserge.com/posts/zig-the-small-language/

Next Steps

Setting up boilerplate code for the ui, keyboard, mouse input and audio output