Blog no. 05
In this blog, we will explore how to link a zig library statically and dynamically.
First lets create a library that contains a function my_add that adds two numbers. Note that instead of pub keyword which we used in previous blog, we will be using export keyword to decorate the my_add function.
// libraries__add.zig
export fn my_add(num1: i32, num2: i32) i32 {
return num1 + num2;
}
Build the libraries__add.zig file as a static library using the command zig build-lib -O ReleaseSafe libraries__add.zig. This will output a liblibraries__add.a file on current folder.
To use this my_add function in our main code to add numbers, we will declare the my_add function's signature in main code using extern keyword. Then at compile time, we will tell the zig compiler to link the liblibraries__add.a with our main output.
// libraries__main1.zig
const std = @import("std");
extern fn my_add(num1: i32, num2: i32) i32;
pub fn main(init: std.process.Init) !void {
// setting up 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("{}+{}={}\n", .{ 5, 6, my_add(5, 6) });
try stdout_writer.flush();
}
Let's build our main code and link liblibraries__add.a with the output using zig build-exe libraries__main1.zig liblibraries__add.a.
The above command will produce a libraries__main1 which when executed will print 5+6=11.
Thanks for reading. To be continued.