Skip to content

Instantly share code, notes, and snippets.

@tribals
Last active March 23, 2025 19:51
Show Gist options
  • Save tribals/87e2e33819ac6258a2022b764b5cfdc0 to your computer and use it in GitHub Desktop.
Save tribals/87e2e33819ac6258a2022b764b5cfdc0 to your computer and use it in GitHub Desktop.
Zig & C library

Zig example to link with system library

Make sure you have libuuid installed on your system, precisely - it's "development" version. It is usually in util-linux package, so install util-linux-dev or the like.

I'm using Guix, if you do too - run this:

$ guix shell -m manifest.scm

Then build a project using standard Zig's facility:

$ zig build

Run it:

$ zig-out/bin/uuidgen
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const uuidgen = b.addExecutable(.{
.name = "uuidgen",
.root_source_file = b.path("main.zig"),
.target = target,
.optimize = optimize,
});
uuidgen.linkLibC();
uuidgen.linkSystemLibrary("uuid");
b.installArtifact(uuidgen);
}
const std = @import("std");
const uuid = @cImport({
@cInclude("uuid/uuid.h");
});
pub fn main() !void {
var v4: [16]u8 = undefined;
// SEE: https://linux.die.net/man/3/uuid_generate
uuid.uuid_generate_random(v4[0..]);
std.debug.print("v4: {x}\n", .{v4});
}
(import
(gnu packages linux)
;; (gnu packages zig-xyz)
(gnu packages zig)
(guix profiles))
(packages->manifest
(list
(list util-linux "lib") ; libuuid
zig-0.14))
;; zig-zls))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment