Chuyển đến nội dung

Bài 29 · C Interop and Build System

Calling C from Zig

Use C libraries from Zig with @cImport and translate-c, map C types and pointers, pass strings and callbacks, export Zig functions to C, and link libc, with a runnable C counterpart.

One of Zig's strongest features is that it can use C code with almost no friction. You do not write bindings by hand and there is no foreign-function layer: Zig contains a C compiler (Clang) and can read C headers directly. That makes the huge world of existing C libraries (SQLite, zlib, SDL, libcurl, OpenSSL...) available on day one, and it lets you migrate a C project one file at a time.

@cImport and @cInclude

Import a C header like this:

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

pub fn main() void {
    _ = c.printf("sqrt(2) = %f\n", c.sqrt(2.0));
}

Everything declared in the headers appears as a member of c: functions, structs, enums, constants, and even simple macros. The build system must link libc for this program (exe.linkLibC() in older code, or .link_libc = true in the module options). If you forget, the compiler tells you that libc is required for the header. Under the hood Zig runs translate-c, which turns the header into Zig declarations; you can see the result with zig translate-c file.h.

Add -D style macros before the include with @cDefine("NAME", "value") in the same block, and group related includes in a single @cImport so they share one translation.

How C types map

C type Zig type
int c_int
unsigned long c_ulong
char u8 (via c_char)
double f64
size_t usize
void * ?*anyopaque
const char * [*c]const u8
T * [*c]T (C pointer)
struct S c.struct_S (or c.S after typedef)

c_int, c_long and friends have the size the target C ABI says, so use them when talking to C and i32/i64 everywhere else. Convert between them with @intCast or @as.

C pointers

A [*c]T pointer is the most permissive pointer type: it may be null, it may point at one item or many, and it coerces to and from Zig pointers. Use it only at the boundary. Convert it to a safe type as soon as you can:

ZIG
const raw: [*c]const u8 = c.getenv("HOME");
if (raw != null) {
    const home = std.mem.span(raw); // []const u8 up to the 0 terminator
    std.debug.print("home = {s}\n", .{home});
}

std.mem.span finds the zero terminator for you. Going the other way, Zig string literals are already zero-terminated and coerce to [*:0]const u8 and [*c]const u8. For runtime-built strings allocate with dupeZ (a [:0]u8), which adds the terminator:

ZIG
const path_z = try gpa.dupeZ(u8, path);
defer gpa.free(path_z);
const file = c.fopen(path_z.ptr, "r");

Working with C structs and out parameters

C functions often fill a struct you provide. Zero it with std.mem.zeroes and pass its address:

ZIG
var tm: c.struct_tm = std.mem.zeroes(c.struct_tm);
var now: c.time_t = c.time(null);
_ = c.localtime_r(&now, &tm);
std.debug.print("year = {d}\n", .{tm.tm_year + 1900});

null is allowed where a C pointer is expected (c.time(null)). C functions that return a status code are just functions returning c_int: convert to a Zig error yourself.

ZIG
fn check(rc: c_int) !void {
    if (rc != 0) return error.CFailed;
}

Callbacks

A C library that wants a function pointer needs a function with the C calling convention. Mark it callconv(.c) (spelled .C in older releases):

ZIG
fn compareInts(a: ?*const anyopaque, b: ?*const anyopaque) callconv(.c) c_int {
    const x: *const c_int = @ptrCast(@alignCast(a));
    const y: *const c_int = @ptrCast(@alignCast(b));
    return if (x.* < y.*) -1 else if (x.* > y.*) 1 else 0;
}

var nums = [_]c_int{ 5, 2, 9, 1 };
c.qsort(&nums, nums.len, @sizeOf(c_int), compareInts);

You must cast anyopaque pointers back to the real type with @ptrCast and @alignCast. This is where bugs creep in, so keep such casts in one small, well-tested function.

Exporting Zig to C

The reverse direction works too. export fn creates a symbol with the C ABI that C code can call:

ZIG
export fn add(a: c_int, b: c_int) c_int {
    return a + b;
}

Build a static or dynamic library from your Zig, and zig build-lib can also produce a header with -femit-h. Structs shared with C must be extern struct (C layout) rather than a normal struct, since Zig may reorder fields of a plain struct:

ZIG
const Point = extern struct { x: f32, y: f32 };

The same applies to enums (enum(c_int)) and unions (extern union). A packed struct has a bit-exact layout for hardware registers and file formats.

Compiling C files with your project

You do not have to rely on a system library. The build system can compile your own C sources next to Zig (see The Zig build system):

ZIG
exe.addCSourceFile(.{ .file = b.path("src/legacy.c"), .flags = &.{"-std=c11"} });

Zig then acts as your C compiler. Even a pure C project can use zig cc as a drop-in replacement for gcc/clang to gain easy cross-compilation (see Cross-compiling and tooling).

Why this matters

flowchart LR
  H["C header<br/>.h"] -->|"@cImport / translate-c"| Z["Zig declarations"]
  Z --> M["your Zig code"]
  M -->|"export fn / extern struct"| C["C callers"]
  S["your .c files"] -->|"addCSourceFile"| B["one zig build"]
  M --> B

Caption: Zig reads C headers, compiles C sources and exports its own functions, in one build.

The C side, runnable

Zig cannot run on this site, so here is the C counterpart of the callback example, which is exactly what the Zig @cImport code above would be calling. It sorts integers with qsort and a C-calling-convention comparison function. Reading it side by side with the Zig code shows what @ptrCast and @alignCast stand for.

C The C side: qsort with a comparison callback

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Forgetting to link libc: @cImport of a libc header then fails to build.
  • Passing a Zig slice where a C string is expected; use a zero-terminated literal or dupeZ.
  • Using i32 where the C type is c_int or long; the sizes can differ by platform.
  • Declaring a struct shared with C as a plain struct; use extern struct.
  • Keeping [*c] pointers deep in your program instead of converting at the boundary.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How does Zig use a C header?

    Zig embeds a C compiler front end and translates headers directly, so C functions and types appear under the imported name.
  2. 2. Which Zig type matches C's int?

    c_int has the size the target C ABI uses for int. Use it at the boundary.
  3. 3. What must a Zig function use to be passed as a C callback?

    C expects its own calling convention, so mark the function accordingly.
  4. 4. How should a struct shared with C be declared?

    extern struct has C's layout; a normal struct lets Zig reorder fields.

Summary

  • @cImport/@cInclude read C headers; link libc where needed.
  • Map C types with c_int, [*c]T, ?*anyopaque; convert C pointers to Zig types early (std.mem.span, dupeZ).
  • Callbacks need callconv(.c); shared structs need extern struct.
  • export fn publishes Zig functions to C, and the build system can compile .c files too.

Next: The Zig build system

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.