🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Header Translation

Header translation is the process of turning a C header file into Zig declarations that Zig code can call. Zig reads the header at compile time and generates matching declarations automatically.

String length from a C header

The string header declares a length function. Zig calls the translated function and prints the result.

const std = @import("std");
const c = @cImport({
    @cInclude("string.h");
});
pub fn main() !void {
    const n = c.strlen("hello");
    const out = std.io.getStdOut().writer();
    try out.print("length={d}\n", .{n});
}

A C struct from a header

The standard library header declares a division function that returns a struct. Zig reads the quotient and remainder fields.

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const d = c.div(17, 5);
    const out = std.io.getStdOut().writer();
    try out.print("quot={d} rem={d}\n", .{ d.quot, d.rem });
}

Text turned into a number

The standard library header declares a text-to-number function. Zig prints the converted value.

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
});
pub fn main() !void {
    const n = c.atoi("42");
    const out = std.io.getStdOut().writer();
    try out.print("number={d}\n", .{n});
}

Example

const std = @import("std");
const c = @cImport({
    @cInclude("stdlib.h");
    @cInclude("string.h");
});
pub fn main() !void {
    const n = c.atoi("123");
    const len = c.strlen("zig");
    const out = std.io.getStdOut().writer();
    try out.print("parsed={d} length={d}\n", .{ n, len });
}

Key points

  • C header: a C header is a file of declarations for functions and types from a C library.
  • Import: an import is the step that brings translated declarations into a Zig file.
  • The @cImport block lists each header to translate with one include line per header.
  • Translated functions keep their C names, so Zig calls them exactly as C spells them.
  • Translated types keep their C sizes, so a C integer in Zig matches the C integer in C.
  • The -lc flag tells Zig to make the C library available to the program.

The example imports two headers in one block. It converts the text 123 into a number and measures the length of zig. It prints both results with one Zig print call.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which header declares the string length function used in this lesson?