Custom Build Options

Hello.

I was wondering if it was possible to provide custom build options in zig. An example might be in C where you can use #ifdef to determine whether an option exists.

In this case, I might specify a build option in build.zig, and want to query the value in my actual program. Does Zig support this use case?

In this case, I might specify a build option in build.zig,
and want to query the value in my actual program.
Does Zig support this use case?

You are looking for std.build.LibExeObjStep.addOptions,
which can be imported later in your program:
https://github.com/ziglang/zig/pull/9623

The solution you linked is just weird in my opinion.

Does Zig not have a better, user-friendly way of allowing user access build options? For me, this hack isn’t good enough.

Anyway, thanks so much for the response!

Does Zig not have a better, user-friendly way of allowing user access
build options? For me, this hack isn’t good enough.

Could you please elaborate? It’s friendly enough to me,
maybe its use in Zig compiler itself is a bit more complex than usual.

In build.zig I have

pub fn build(b: *Builder) void {
    const options = b.addOptions();
    options.addOption(Type, "foo", value);

    const exe = b.addExecutable("executable", "path/to/root.zig");
    exe.addOptions("build_options", options);
    ...
}

and in the codebase I can simply

const foo = @import("build_options").foo;

This allows you to have namespaced build options, unlike e.g. -D in C.

2 Likes

Sorry, I couldn’t find such an example…

With your code example, this is definitely user-friendly!

2 Likes

Also, can you please give an example of how one would set the option in the terminal?

Is it with the -Dflag just like the global build options?

Also, can you please give an example of how one would
set the option in the terminal?

Is it with the -Dflag just like the global build options?

Yes, you could use something like

options.addOption(bool, "flag",
    b.option(bool, "flag", "Whether to wave"));

Builder.option simply parses the specified CLI argument
and returns the value (plus generating the --help message).

3 Likes