🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Extern Functions

An extern function is a function declared in Zig but defined in another language. Its body lives in the C library, not in the Zig file.

Absolute value by declaration

This program declares the absolute value function by hand. The call then works like any other function call.

const std = @import("std");
extern fn abs(x: c_int) c_int;
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("abs: {d}\n", .{abs(-17)});
}

Parsing a number

A parsing function turns digits in text into a number. It keeps the sign when the text starts with a minus sign.

const std = @import("std");
extern fn atoi(s: [*:0]const u8) c_int;
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("atoi: {d}\n", .{atoi("42")});
    try out.print("atoi: {d}\n", .{atoi("-7")});
}

Length and letters by declaration

More than one function can be declared in the same file. This program declares length, case conversion, and a digit test together.

const std = @import("std");
extern fn strlen(s: [*:0]const u8) usize;
extern fn toupper(c: c_int) c_int;
extern fn isdigit(c: c_int) c_int;
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("len: {d}\n", .{strlen("zig")});
    const up: u8 = @intCast(toupper('z'));
    try out.print("upper: {c}\n", .{up});
    if (isdigit('7') != 0) {
        try out.print("7 is a digit\n", .{});
    }
    if (isdigit('x') == 0) {
        try out.print("x is not a digit\n", .{});
    }
}

Example

const std = @import("std");
extern fn atoi(s: [*:0]const u8) c_int;
extern fn abs(x: c_int) c_int;
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const parsed = atoi("-25");
    try out.print("parsed: {d}\n", .{parsed});
    try out.print("absolute: {d}\n", .{abs(parsed)});
}

Key points

  • Extern declaration: an extern declaration is a function header with no body that names a function defined elsewhere.
  • Signature: a signature is the list of parameter types and the return type of a function.
  • C integer: a C integer is an integer type whose size follows the C rules on the target machine.
  • A declared function can be called exactly like an ordinary Zig function.
  • The C library must still be linked, so every block that calls a declared C function runs with the -lc flag.
  • Declarations must match the real C function, or the call can read the wrong value.

The program parses the text into a negative number first. It then takes the absolute value of that number. The two printed lines show the input value and its positive size.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does an extern function declaration contain?