TExcelTAD
Home › Zig › Zig C Interop

Zig C Interop

C is the common language of systems programming: operating system APIs, graphics drivers, databases and countless libraries expose C interfaces. Zig was designed to work with C without bindings or wrappers. It can import C header files directly, call C functions, export Zig functions to C, and even compile C source code.

Note: The playground compiles single Zig files without linking libc, so this lesson's C examples are shown as files and terminal sessions. The pure-Zig parts — C-compatible types and calling conventions — do run.

Importing a C header

@cImport translates a C header into Zig declarations at compile time. Then you call the C functions like any other function:

zig
const c = @cImport({
    @cInclude("stdio.h");
    @cInclude("math.h");
});

pub fn main() void {
    _ = c.printf("sqrt(2) from libc: %.4f\n", c.sqrt(2.0));
}
bash · try it yourself
zig run hello_c.zig -lc
sqrt(2) from libc: 1.4142

-lc links the C standard library. Zig ships libc headers and implementations (musl, glibc stubs, MinGW) for many targets, so this works even when cross-compiling.

Tip: Zig 0.15 is gradually moving @cImport to the build system (b.addTranslateC), but @cImport still works and is the quickest way to experiment.

C types in Zig

C Zig
int, long, unsigned int c_int, c_long, c_uint
char u8 (or c_char)
float, double f32, f64
const char * (string) [*:0]const u8
T * (may be NULL) ?*T or [*c]T
void * ?*anyopaque
struct with C layout extern struct
size_t usize

The c_int family matches the C compiler's sizes for the target, which can differ between platforms (a c_long is 8 bytes on 64-bit Linux, 4 bytes on Windows).

zig · try it yourself
const std = @import("std");

const CPoint = extern struct {
    x: c_int,
    y: c_int,
    label: [*:0]const u8,
};

pub fn main() void {
    const p = CPoint{ .x = 3, .y = -1, .label = "origin-ish" };
    std.debug.print("c_int is {d} bytes, c_long is {d} bytes\n", .{ @sizeOf(c_int), @sizeOf(c_long) });
    std.debug.print("CPoint is {d} bytes, label offset {d}\n", .{ @sizeOf(CPoint), @offsetOf(CPoint, "label") });
    std.debug.print("{s} at ({d}, {d})\n", .{ p.label, p.x, p.y });
}
c_int is 4 bytes, c_long is 8 bytes
CPoint is 16 bytes, label offset 8
origin-ish at (3, -1)

An extern struct keeps fields in declaration order with C padding rules, so it can be passed to and from C code safely.

Strings across the boundary

C strings end with a zero byte; Zig slices carry a length. Converting between them is the most common interop task:

zig · try it yourself
const std = @import("std");

// pretend this came from a C function returning `const char *`
fn cGetName() [*:0]const u8 {
    return "libexample";
}

// a function with the C calling convention, callable from C
fn cStringLength(s: [*:0]const u8) callconv(.c) usize {
    return std.mem.len(s);
}

pub fn main() void {
    const name: []const u8 = std.mem.span(cGetName()); // C string -> Zig slice
    std.debug.print("{s} has {d} bytes\n", .{ name, name.len });

    const literal: [*:0]const u8 = "zero-terminated"; // literals already end in 0
    std.debug.print("length via C-style function: {d}\n", .{cStringLength(literal)});
}
libexample has 10 bytes
length via C-style function: 15

For a runtime Zig slice without a terminator, make a terminated copy with allocator.dupeZ(u8, slice) before passing it to C.

Exporting Zig to C

export makes a function visible to C with the C calling convention. Build it as a library and C code can call it like any C function:

zig
// mathlib.zig
export fn add_clamped(a: c_int, b: c_int, max: c_int) c_int {
    return @min(a + b, max);
}
c
// main.c
#include <stdio.h>
int add_clamped(int a, int b, int max);

int main(void) {
    printf("%d\n", add_clamped(40, 5, 42));
    return 0;
}
bash · try it yourself
zig build-lib mathlib.zig -dynamic
zig cc main.c -L. -lmathlib -o main
LD_LIBRARY_PATH=. ./main
42

zig cc: a drop-in C compiler

zig cc and zig c++ are full Clang-based C/C++ compilers with cross-compilation built in. Many projects that contain no Zig code at all use them to cross-compile C:

bash
zig cc -target aarch64-linux-musl hello.c -o hello-arm64
zig c++ -target x86_64-windows-gnu app.cpp -o app.exe

Translating whole files

zig translate-c header.h prints the Zig translation of a header, which is useful to see how C types and macros are mapped. Simple #define constants become Zig constants; complicated function-like macros may not translate and need a small hand-written Zig wrapper.

Test yourself

Which builtin imports declarations from a C header?

  1. @import
  2. @cImport with @cInclude
  3. @include
  4. extern "C"

What is the Zig type for a C string parameter const char *?

  1. []const u8
  2. [*:0]const u8
  3. *u8
  4. String

Why use extern struct for data shared with C?

  1. It is faster
  2. It guarantees C-compatible field order and padding
  3. It allows methods
  4. It makes fields optional