🎓 A1Learner
🔍
0 of 46 lessons completed

Zig C Imports

C import is a way to use functions from the C library inside Zig code. A header lists the functions that are available.

String length

The string header offers a length function for C strings. It counts the characters before the end marker.

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

Absolute value

The standard header offers an absolute value function. It turns a negative number into its positive size.

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

Letter case and digits

The character header offers tests and conversions for single letters. One conversion turns a lowercase letter into its uppercase form.

const std = @import("std");
const c = @cImport({
    @cInclude("ctype.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const upper: u8 = @intCast(c.toupper('a'));
    try out.print("upper: {c}\n", .{upper});
    if (c.isdigit('7') != 0) {
        try out.print("7 is a digit\n", .{});
    }
    if (c.isdigit('x') == 0) {
        try out.print("x is not a digit\n", .{});
    }
}

Example

const std = @import("std");
const c = @cImport({
    @cInclude("string.h");
});
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const len = c.strlen("apple");
    try out.print("length: {d}\n", .{len});
    const cmp = c.strcmp("apple", "banana");
    if (cmp < 0) {
        try out.print("apple comes first\n", .{});
    }
}

Key points

  • C library: a C library is a collection of ready-made functions written in C.
  • Header: a header is a file that lists the functions a C library offers.
  • C import: a C import is a Zig block that reads C headers and makes their functions usable.
  • Linking: linking is the step that connects a program to the C library it uses.
  • The C library must be linked, so every C block in this course runs with the -lc flag.
  • A C function result can be printed with the usual Zig output pattern.

The program measures the first word and compares the two words. The comparison result is negative when the first word sorts first. Only the matching message is printed, so the output shows both facts.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which flag must a C import block be run with?