#Passing compile time options into a zig program and using them

1 messages · Page 1 of 1 (latest)

next kraken
#

I'm just playing around honestly, but is this possible? I'm looking for something similar to defining -Dsomeflag and using it like you would do something in c:

#ifdef someflag
#endif

So far I have come across exe.addOptions but I am unsure of how to actually use it in the zig file.

floral coral
#
const build_options = b.addOptions();
build_options.addOption(bool, "someflag", b.option(bool, "someflag", "description") orelse false);

exe.addOptions("build_options", build_options);
const build_options = @import("build_options");
fn f() void {
    if (build_options.someflag) {
    } else {
    }
}
next kraken
#

Works like a charm thanks 🙂 Can you also do this for individual modules in your project out of curiosity?

floral coral
#
const build_options = b.addOptions();
build_options.addOption(bool, "someflag", b.option(bool, "someflag", "description") orelse false);
const build_options_module = build_options.createModule();

const my_module = b.addModule("mymodule", .{
    .source = .{ .path = "src/mymodule.zig" },
    .dependencies = &.{
        .{ .name = "build_options", .module = build_options_module },
    },
});
exe.addModule("mymodule", my_module);