Access the version of your binary inside of it

In my build.zig I use the addExecutable method and in it I set a version of my executable.
Is it possible to access this value in the program?

In rust for example I can do this:

const VERSION: &str = env!("CARGO_PKG_VERSION");

Otherwise it’s easy to forget to up the version everywhere

You can use option at the build.zig to refer on source code.

build.zig

const build_options = b.addOptions();
build_options.addOption([]const u8, "version", "0.1.0");
exe.root_module.addOptions("build_options", build_options);

main.zig

const build_options = @import("build_options"); // name passed to `exe.addOptions`

pub fn main() void {
    std.debug.pring("{s}\n", .{build_options.version});
}

See also Build system tricks

    1. Declare user options upfront
    1. Declare every major Compile or Run step upfront
3 Likes

The example in @ktz_alias’s comment is also what the Zig binary itself does:

1 Like