Set compile time constant

Zig newbie here.

I’d like to set a constant at compile time.

In golang I can use the linker:
go build -ldflags="-X 'main.Version=v1.0.0'"

I could just substitute a placeholder, but is there anything more elegant?

I’ve tried a comptime using Env Vars but std.os.environ is not comptime compatible

What is the easiest way to do this in Zig?

Thanks!

First you define an option in your build.zig:

Build System Tricks - declare user options

const is_enabled = b.option(bool, "is_enabled", "Enable some capability") orelse false;

const options = b.addOptions();
options.addOption(bool, "is_enabled", is_enabled);

You then add the options:

exe.root_module.addOptions("config", options);

And within the source code use @import("config") to access it from the source code.

Then when you run zig build --help it is listed under “Project-Specific Options”.

4 Likes