Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://lazyfoo.net/tutorials/SDL/01_hello_SDL/index2.php
- // in zig, to prove just how drop in c compatibility really is:
- // You can also add C files to your builds without a problem, so this
- // should be useful when transitioning large code bases to zig. In
- // addition to this, you can also write zig to export a C abi
- // (but I'm not sure if there are any automatic header generation
- // tools).
- const std = @import("std");
- const print = std.debug.print;
- // See @cDefine @cUndef and the zig translate-c tool if you need more
- // control over c includes
- const s = @cImport({
- @cInclude("SDL2/SDL.h");
- // You can have as many includes as you want...
- // In this case I'm not really going to use stdio.h, but whatever
- @cInclude("stdio.h");
- });
- const SCREEN_WIDTH = 640;
- const SCREEN_HEIGHT = 480;
- pub fn main() u8 {
- // Window is an opaque type, so we use a normal pointer
- var window: *s.SDL_Window = undefined;
- // [*c] is a c pointer, to help with c interop
- var surface: [*c]s.SDL_Surface = 0;
- // Zig is very annoying with unused variables, so if there's a
- // var you haven't gotten to using yet, just do _ = your_var; and
- // that'll shut it up (it's a noop):
- _ = window;
- if (s.SDL_Init(s.SDL_INIT_VIDEO) < 0) {
- print("SDL could not initialize! SDL_Error: {s}\n",
- .{s.SDL_GetError()});
- return 1;
- }
- // There is also a errdefer which only fires if the function
- // returns an error
- defer s.SDL_Quit();
- window = s.SDL_CreateWindow("SDL Tutorial",
- s.SDL_WINDOWPOS_UNDEFINED,
- s.SDL_WINDOWPOS_UNDEFINED,
- SCREEN_WIDTH,
- SCREEN_HEIGHT,
- s.SDL_WINDOW_SHOWN) orelse {
- // orelse fires if the result is null
- print("Window could not be created! SDL_Error: {s}\n",
- .{s.SDL_GetError()});
- return 2;
- };
- defer s.SDL_DestroyWindow(window);
- surface = s.SDL_GetWindowSurface(window);
- // _ = * is needed to ignore return values as well
- _ = s.SDL_FillRect(surface, null,
- s.SDL_MapRGB(surface.*.format, 0xF0, 0xF0, 0xF0));
- _ = s.SDL_UpdateWindowSurface(window);
- s.SDL_Delay(2000);
- return 0;
- }
- // And the build script looks like this:
- ///////////////////////////////////////////////////////////////////////
- // ... //
- // const exe = b.addExecutable("zigcheatsheet", "src/main.zig"); //
- // exe.linkLibC(); //
- // exe.addIncludeDir("/usr/include"); //
- // exe.linkSystemLibrary("SDL2"); //
- // exe.setTarget(target); //
- // exe.setBuildMode(mode); //
- // exe.install(); //
- // ... //
- ///////////////////////////////////////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement