Building Statically Linked Go Executables with CGO and Zig
Published on: 2025-05-24 21:11:07
Building Statically Linked Go Executables with CGO and Zig
This is a short post about how to create a statically linked Go executable that calls in to CGO dependencies using Zig. The full code for this post is available in this repo.
By default, if you're using CGO, the executable you generate dynamically links, but I frequently want to statically link to avoid runtime errors.
First, let's create a zig library, with zig init, then trim back the excess stuff it generates so we're left just with a simple static library. You can rm src/main.zig since we're not creating a zig executable.
Next, we can trim build.zig to just:
// build.zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const lib_mod = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, }); const lib = b.addLibrary(.{ .linkage = .static, .name = "cgo_static_linking"
... Read full article.