Skip to content

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.

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...OK
All 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 plain add could clash with another library’s add.
  • 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.

C code needs a header that declares your functions. Write it by hand; it’s short:

mathzig.h
#ifndef MATHZIG_H
#define MATHZIG_H
#include <stddef.h>
int mz_add(int a, int b);
size_t mz_count_vowels(const char *text);
#endif

Each line mirrors a Zig signature: c_int is int, usize is size_t, [*:0]const u8 is const char *.

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:

Terminal window
zig build-lib mathzig.zig

Here’s the C program:

main.c
#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:

Terminal window
zig cc main.c libmathzig.a -o main
./main

You’ll see:

mz_add(40, 2) = 42
vowels in "Hello Zig": 3

That’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.a fails with relocation 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 debug library carries debug info and safety-check code. Our tiny one-function library was about 10 MB as a debug build and under 4 KB with -O fast (measured on our Linux machine; yours will differ a bit). Ship release builds: -O safe keeps the safety checks, -O fast drops them.

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:

Terminal window
zig build-lib mathzig.zig -dynamic -O fast
gcc main.c -L. -lmathzig -o main-dyn
LD_LIBRARY_PATH=. ./main-dyn

You’ll see:

mz_add(40, 2) = 42
vowels 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.

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 representation

Neither 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.

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...OK
All 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);
#endif

c/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) = 42
distance = 5.0
parsed 123
"12x" is not a number

What’s going on:

  • b.addLibrary(.{ .linkage = .static, ... }) builds the library. Use .linkage = .dynamic for a shared one.
  • lib.installHeader(...) copies the header into zig-out/include/ when you run zig build, next to zig-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.
  • Point is an extern struct, so its layout matches the C typedef struct, and it can be passed by value both ways.
  • mz_parse_int shows the error pattern: Zig’s catch turns an error into -1, and the real result goes out through out.

Plain zig build (without run) leaves zig-out/lib/libmathzig.a, zig-out/include/mathzig.h and zig-out/bin/app.

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_allocator uses C’s malloc and free, 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_free accepts NULL and does nothing, like C’s own free. Callers appreciate that.
  • Running the C program under valgrind --leak-check=full reported “All heap blocks were freed”, so the pair really does clean up.

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 3
pan.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.

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...OK
All 1 tests passed.

The header line is int mz_max(int a, int b);.

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...OK
All 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.

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...OK
All 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 fn makes 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-h didn’t produce a file in 0.17.1.
  • zig build-lib makes a static library, -dynamic a shared one; in build.zig use b.addLibrary and installHeader.
  • 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

1. What does export do to a Zig function?
2. Why can't an exported function take a []const u8?
3. Your Zig library returns a string allocated with std.heap.c_allocator. How should the C caller free it?
4. gcc says recompile with -fPIE when linking your static Zig library. What do you do?