Zig Exporting to C
So far C code has been doing the work and Zig has been calling it. This page turns that around: you write a library in Zig, and a C program (or Python, Go, Rust, anything that can call C) uses it. This is one of Zig’s real strengths. You get Zig’s safety checks, tests and build system while writing the code, and your users get a plain C library with a plain C header. They don’t need to know it was written in Zig.
export fn
Section titled “export fn”The keyword is export. It does two things to a function: it uses the C calling convention, and it puts the function’s name into the compiled library so other code can find it.
const std = @import("std");
export fn mz_add(a: c_int, b: c_int) c_int { return a + b;}
export fn mz_count_vowels(text: [*:0]const u8) usize { const s = std.mem.span(text); var count: usize = 0; for (s) |c| { switch (std.ascii.toLower(c)) { 'a', 'e', 'i', 'o', 'u' => count += 1, else => {}, } } return count;}
test "exported functions are still Zig functions" { try std.testing.expectEqual(42, mz_add(40, 2)); try std.testing.expectEqual(3, mz_count_vowels("Hello Zig"));}Output:
1/1 main.test.exported functions are still Zig functions...OKAll 1 tests passed.Notice the test at the bottom. An exported function is still a normal Zig function, so you can test it from Zig before any C code ever touches it. That’s a big part of why writing a C library in Zig is pleasant.
Two habits from C libraries worth keeping:
- Prefix every name (
mz_here, for “math zig”). C has one global namespace, so a plainaddcould clash with another library’sadd. - Use C types in the signature (
c_int,usize,[*:0]const u8) so the header matches on every platform. Zig and C has the full table.
Write the header
Section titled “Write the header”C code needs a header that declares your functions. Write it by hand; it’s short:
#ifndef MATHZIG_H#define MATHZIG_H
#include <stddef.h>
int mz_add(int a, int b);size_t mz_count_vowels(const char *text);
#endifEach line mirrors a Zig signature: c_int is int, usize is size_t, [*:0]const u8 is const char *.
Build a static library and use it from C
Section titled “Build a static library and use it from C”zig build-lib compiles a Zig file into a library. By default you get a static library, libmathzig.a, which gets copied into each program that uses it:
zig build-lib mathzig.zigHere’s the C program:
#include <stdio.h>#include "mathzig.h"
int main(void) { printf("mz_add(40, 2) = %d\n", mz_add(40, 2)); printf("vowels in \"Hello Zig\": %zu\n", mz_count_vowels("Hello Zig")); return 0;}Compile it and link the library. Any C compiler works; zig cc is right there:
zig cc main.c libmathzig.a -o main./mainYou’ll see:
mz_add(40, 2) = 42vowels in "Hello Zig": 3That’s a C program calling Zig code, with no wrappers in between.
Two practical notes:
- Linking with gcc. Most Linux distributions make gcc build “position-independent executables” (PIE) by default, and then
gcc main.c libmathzig.afails withrelocation R_X86_64_32S ... can not be used when making a PIE object; recompile with -fPIE. The fix is what it says:zig build-lib mathzig.zig -fPIE. - Build mode. A
debuglibrary carries debug info and safety-check code. Our tiny one-function library was about 10 MB as adebugbuild and under 4 KB with-O fast(measured on our Linux machine; yours will differ a bit). Ship release builds:-O safekeeps the safety checks,-O fastdrops them.
Shared libraries
Section titled “Shared libraries”For a shared library (.so on Linux, .dylib on macOS, .dll on Windows) add -dynamic. Programs load it when they start instead of copying it in:
zig build-lib mathzig.zig -dynamic -O fastgcc main.c -L. -lmathzig -o main-dynLD_LIBRARY_PATH=. ./main-dynYou’ll see:
mz_add(40, 2) = 42vowels in "Hello Zig": 3-L. tells the linker to look for libraries in the current folder, -lmathzig means libmathzig.so, and LD_LIBRARY_PATH=. tells Linux where to find it at run time. Shared libraries are also how other languages usually load C code: Python’s ctypes, for example, can open libmathzig.so and call mz_add directly.
What can cross the border
Section titled “What can cross the border”C only understands C types, so export only accepts them. A slice has no C equivalent:
export fn count_bytes(text: []const u8) usize { return text.len;}
pub fn main() void {}main.zig:1:23: error: parameter of type '[]const u8' not allowed in function with calling convention 'x86_64_sysv'export fn count_bytes(text: []const u8) usize { ^~~~~~~~~~~~~~~~main.zig:1:23: note: slices have no guaranteed in-memory representationNeither does an error union:
export fn parse(text: [*:0]const u8) !i32 { _ = text; return error.Nope;}
pub fn main() void {}main.zig:1:39: error: return type '!i32' not allowed in function with calling convention 'x86_64_sysv'export fn parse(text: [*:0]const u8) !i32 { ^~~(x86_64_sysv is the name of the C calling convention on 64-bit Linux and macOS.) The usual C-style replacements:
| In Zig you’d use | Across the C border use |
|---|---|
a slice []const T |
a pointer plus a length: ptr: [*]const T, len: usize |
a string []const u8 |
[*:0]const u8 (or pointer plus length) |
an error union !T |
return a status code (c_int, 0 for success) and write the result through a pointer |
an optional pointer ?*T |
?*T works as is: NULL means none |
| a struct | an extern struct |
| an enum | an enum(c_int) |
Inside the function, turn the C-style arguments straight back into Zig: ptr[0..len] makes a slice, and std.mem.span(text) turns a C string into one.
A fuller example with build.zig
Section titled “A fuller example with build.zig”Let’s put it together in a project: a Zig library with a struct and a function that can fail, a header, and a C program, all built by zig build.
src/root.zig:
const std = @import("std");
pub const Point = extern struct { x: f64, y: f64,};
export fn mz_add(a: c_int, b: c_int) c_int { return a + b;}
export fn mz_distance(a: Point, b: Point) f64 { const dx = a.x - b.x; const dy = a.y - b.y; return @sqrt(dx * dx + dy * dy);}
/// Returns 0 on success, -1 if `text` is not a valid number.export fn mz_parse_int(text: [*:0]const u8, out: *c_int) c_int { out.* = std.fmt.parseInt(c_int, std.mem.span(text), 10) catch return -1; return 0;}
test "mz_parse_int" { var n: c_int = 0; try std.testing.expectEqual(0, mz_parse_int("123", &n)); try std.testing.expectEqual(123, n); try std.testing.expectEqual(-1, mz_parse_int("12x", &n));}Output:
1/1 main.test.mz_parse_int...OKAll 1 tests passed.include/mathzig.h:
#ifndef MATHZIG_H#define MATHZIG_H
typedef struct { double x; double y;} Point;
int mz_add(int a, int b);double mz_distance(Point a, Point b);/* Returns 0 on success, -1 if text is not a valid number. */int mz_parse_int(const char *text, int *out);
#endifc/main.c:
#include <stdio.h>#include "mathzig.h"
int main(void) { printf("mz_add(40, 2) = %d\n", mz_add(40, 2));
Point a = {0, 0}; Point b = {3, 4}; printf("distance = %.1f\n", mz_distance(a, b));
int n; if (mz_parse_int("123", &n) == 0) printf("parsed %d\n", n); if (mz_parse_int("12x", &n) != 0) printf("\"12x\" is not a number\n"); return 0;}And build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
// The Zig library. const lib = b.addLibrary(.{ .name = "mathzig", .linkage = .static, .root_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, }), }); lib.installHeader(b.path("include/mathzig.h"), "mathzig.h"); b.installArtifact(lib);
// A C program that uses it. const app_mod = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true, }); app_mod.addCSourceFile(.{ .file = b.path("c/main.c") }); app_mod.linkLibrary(lib);
const app = b.addExecutable(.{ .name = "app", .root_module = app_mod, }); b.installArtifact(app);
const run_step = b.step("run", "Run the C program"); run_step.dependOn(&b.addRunArtifact(app).step);}zig build run prints:
mz_add(40, 2) = 42distance = 5.0parsed 123"12x" is not a numberWhat’s going on:
b.addLibrary(.{ .linkage = .static, ... })builds the library. Use.linkage = .dynamicfor a shared one.lib.installHeader(...)copies the header intozig-out/include/when you runzig build, next tozig-out/lib/libmathzig.a. That folder pair is what you’d hand to C users.app_mod.linkLibrary(lib)links the library into the C program, and also makes its installed header visible to the C compiler, which is why#include "mathzig.h"just works.Pointis anextern struct, so its layout matches the Ctypedef struct, and it can be passed by value both ways.mz_parse_intshows the error pattern: Zig’scatchturns an error into-1, and the real result goes out throughout.
Plain zig build (without run) leaves zig-out/lib/libmathzig.a, zig-out/include/mathzig.h and zig-out/bin/app.
Strings and memory: who frees what
Section titled “Strings and memory: who frees what”Returning a string that Zig created brings up the next problem: who frees it? C’s free can’t safely free memory from just any Zig allocator. The safe rule for any library, in any language: memory is freed by the library that allocated it. So you export a matching free function:
const std = @import("std");
const gpa = std.heap.c_allocator;
/// Returns a new string "Hello, <name>!" or NULL if memory runs out./// Free it with greet_free.export fn greet_new(name: [*:0]const u8) ?[*:0]u8 { const text = gpa.printSentinel("Hello, {s}!", .{std.mem.span(name)}, 0) catch return null; return text.ptr;}
export fn greet_free(text: ?[*:0]u8) void { const t = text orelse return; gpa.free(std.mem.span(t));}The C side:
char *msg = greet_new("Ada");if (msg == NULL) return 1;printf("%s\n", msg);greet_free(msg);Built with zig build-lib greet.zig -lc and linked like before, you’ll see:
Hello, Ada!Details worth copying:
std.heap.c_allocatoruses C’smallocandfree, so the library needs libc (-lc). It’s a good fit for a C library, since that’s what its users expect.printSentinel(..., 0)builds the text with a zero at the end, so C can read it as a normal string.greet_freeaccepts NULL and does nothing, like C’s ownfree. Callers appreciate that.- Running the C program under
valgrind --leak-check=fullreported “All heap blocks were freed”, so the pair really does clean up.
Panics stop the whole program
Section titled “Panics stop the whole program”A Zig library still has Zig’s safety checks (in debug and safe builds). If C calls your function with a bad index, the check fires and the whole C program stops:
thread 24724 panic: index out of bounds: index 5, len 3pan.zig:3:17: 0x1026f58 in get_item (pan.zig) return items[index]; ^That’s usually better than C’s silent memory corruption, but a library shouldn’t crash its users on input it could have checked. For anything that comes from the caller (indexes, lengths, strings to parse), check it and return an error code instead of trusting it. Save panics for real bugs in your own code.
Practice
Section titled “Practice”1. Export a function
Section titled “1. Export a function”Write export fn mz_max(a: c_int, b: c_int) c_int that returns the larger number, plus a Zig test for it. Then write the line for the C header.
Hint: @max(a, b) works on c_int.
Show solution
const std = @import("std");
export fn mz_max(a: c_int, b: c_int) c_int { return @max(a, b);}
test "mz_max" { try std.testing.expectEqual(7, mz_max(3, 7)); try std.testing.expectEqual(-1, mz_max(-1, -5));}Output:
1/1 main.test.mz_max...OKAll 1 tests passed.The header line is int mz_max(int a, int b);.
2. Pointer and length instead of a slice
Section titled “2. Pointer and length instead of a slice”Write export fn mz_sum(values: [*]const c_int, len: usize) c_int that adds up len numbers. Turn the pointer into a slice inside the function, and test it from Zig.
Hint: const items = values[0..len]; then loop over items.
Show solution
const std = @import("std");
export fn mz_sum(values: [*]const c_int, len: usize) c_int { const items = values[0..len]; var total: c_int = 0; for (items) |v| total += v; return total;}
test "mz_sum" { const numbers = [_]c_int{ 1, 2, 3, 4 }; try std.testing.expectEqual(10, mz_sum(&numbers, numbers.len));}Output:
1/1 main.test.mz_sum...OKAll 1 tests passed.In C it’s int mz_sum(const int *values, size_t len);. As soon as you’re inside the function, values[0..len] gives you a normal Zig slice with bounds checks.
3. Fix the export
Section titled “3. Fix the export”This doesn’t compile. Change the signature so C can call it, returning 0 for “ok” and -1 for “empty”, with the length written through a pointer.
export fn mz_name_length(name: []const u8) !usize { if (name.len == 0) return error.Empty; return name.len;}Hint: take a [*:0]const u8 and an out: *usize, and return c_int.
Show solution
const std = @import("std");
export fn mz_name_length(name: [*:0]const u8, out: *usize) c_int { const s = std.mem.span(name); if (s.len == 0) return -1; out.* = s.len; return 0;}
test "mz_name_length" { var len: usize = 0; try std.testing.expectEqual(0, mz_name_length("Zig", &len)); try std.testing.expectEqual(3, len); try std.testing.expectEqual(-1, mz_name_length("", &len));}Output:
1/1 main.test.mz_name_length...OKAll 1 tests passed.The slice became a C string, the error union became a status code, and the real result goes out through out.
export fnmakes a Zig function callable from C: C calling convention, name visible in the library.- Only C-compatible types can cross: C integers, pointers,
[*:0]const u8,extern struct. No slices, no error unions. - Use pointer + length for slices and status codes + out pointers for errors.
- Write the C header by hand;
-femit-hdidn’t produce a file in 0.17.1. zig build-libmakes a static library,-dynamica shared one; inbuild.ziguseb.addLibraryandinstallHeader.- Memory is freed by the library that allocated it: export a free function next to anything that allocates.
- Exported functions are still Zig functions, so test them in Zig first.
Next up: Zig Interfaces, the vtable pattern behind std.mem.Allocator and std.Io, and how to build your own.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Exporting a C library (0.17.1 reference):
export, static and shared libraries, and abuild.zigexample. - export (0.17.1 reference): what
exportmeans for functions and variables. - Mixing object files (0.17.1 reference): linking a Zig object file into a C program, using the pointer-and-length pattern.
- Zig Build System guide: libraries, installing headers and linking.