liveBook · Manning

Main function

As explained in Systems Programming with Zig

A main function is the designated entry point that begins execution of a program.

A main function is a program’s designated entry point. In Zig, runtime functions are called from main, either directly or through other functions. section 2.1

Listing 2.1 A simple program
const std = @import("std"); #1

pub fn main() void { #2
    const x: i32 = 42; #3
    std.debug.print("{}\n", .{x}); #4
}

This Zig program imports the standard library, then uses main to print 42. The declaration pub fn main() void defines a public function that returns no value. section 2.1

The pub keyword matters: removing it from main produces a compiler error that says main is not marked pub. Statements in the function’s braces execute in order when it is called. section 2.1.4 section 2.1

Listing 2.4 main.zig
const std = @import("std");
const fibonacci = @import("fibonacci.zig").fibonacci; #1

pub fn main() void {
    const first = fibonacci(1);
    const second = fibonacci(2);
    const third = fibonacci(3);
    const fourth = fibonacci(4);
    std.debug.print("{} {} {} {}\n", .{ first, second, third, fourth });
}

Main can delegate work to a function in another file. Here, @import("fibonacci.zig").fibonacci accesses a public function, calls it four times, and prints the results. The imported function must be marked pub to be accessible from this file. section 2.1.4

How Systems Programming with Zig covers it

How deep it goes
Explains main’s declaration, public visibility, function body, and calls across files without detailing startup implementation.
Examples
Shows a program printing 42 and another importing Fibonacci to print four results.
What it assumes
Assumes familiarity with imperative program structure while introducing Zig imports and modules.
What you can do after
Builds a Zig entry point that prints values and calls a public function imported from another file.
How it connects
Connects main to runtime, function calls, modules, imports, and namespaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.