DEV Community

Cover image for You have been zigged (series) : Writing a program in multiple files
Black Tornado
Black Tornado

Posted on

You have been zigged (series) : Writing a program in multiple files

In this program, we'll write a program to find the absolute of a 32 bit signed integer. We will purposefully break the program into 2 files to see how to modularize zig codebase. Spoiler alert - its done using @import built-in.

First, lets save multiple_source_files__myabs.zig with myabs function that returns absolute value of a number. Its a very simple function.

// multiple_source_files__myabs.zig
pub fn myabs(num: i32) i32 {
    return if (num < 0) -num else num;
}
Enter fullscreen mode Exit fullscreen mode

Now lets save multiple_source_files__main.zig with the following content. This outer program which contains an entry point uses the @import built-in to import the previously made multiple_source_files__myabs.zig type and call the myabs function we defined in it.

// multiple_source_files__main.zig
const std = @import("std");
const myabsType = @import("./multiple_source_files__myabs.zig");

pub fn main(init: std.process.Init) !void {
    const num: i32 = -1;
    const abs_num = myabsType.myabs(num);

    // setup stdout writer
    var buffer: [1024]u8 = undefined;
    var file_writer = std.Io.File.Writer.init(.stdout(), init.io, &buffer);
    var stdout_writer = &file_writer.interface;

    try stdout_writer.print("The absolute value of {} is {}\n", .{ num, abs_num });
    try stdout_writer.flush();
}
Enter fullscreen mode Exit fullscreen mode

We don't need to compile the multiple_source_files__myabs.zig to object file first and then link it against the compilation of multiple_source_files__main.zig. Instead, we can do it in one go using zig build-exe -O ReleaseSafe multiple_source_files__main.zig and the import built-in will take care of the rest. This will work only when your myabs function and the code that uses it are written in zig. So what happens when you need to use the C ABI ? We will see it in next blog. :-)

Thanks for reading. To be continued.

Top comments (0)