C Types

Zig has a set of primitive types for use with C.

Let’s say we want to call the pow function defined here:

/* ints.c */
long pow(int x, unsigned short n) {
    long result = 1;
    do result *= x; while (--n);
    return result;
}

The c_ types will match the C types on the target platform:

const std = @import("std");
const expectEqual = std.testing.expectEqual;
const c = @import("c");

test "calling pow with the right types" {
    const x: c_int = 10;
    const n: c_ushort = 2;
    const got: c_long = c.pow(x, n);
    const want: c_long = 100;
    try expectEqual(want, got);
}

We’ll use a build.zig similar to the one in Using C.

const std = @import("std");

pub fn build(b: *std.Build) void {
    const root_source_file = b.path("ints.zig");

    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    // addTranslateC works for .c and .h files.
    const translate_c = b.addTranslateC(.{
        .root_source_file = b.path("ints.c"),
        .target = target,
        .optimize = optimize,
    });
    const c_module = translate_c.createModule();

    const exe = b.addExecutable(.{
        .name = "ints",
        .root_module = b.createModule(.{
            .root_source_file = root_source_file,
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{
                    .name = "c",
                    .module = c_module,
                },
            },
        }),
    });
    b.installArtifact(exe);

    const test_step = b.step("test", "Run unit tests");
    const unit_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = root_source_file,
            .target = target,
            .imports = &.{
                .{
                    .name = "c",
                    .module = c_module,
                },
            },
        }),
    });
    const run_unit_tests = b.addRunArtifact(unit_tests);
    test_step.dependOn(&run_unit_tests.step);
}

The test passes, so no output:

zig build test

Next example: Time and Date.