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?
cnx
April 12, 2022, 3:40am
2
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:
ziglang:master
ā leecannon:master
opened 07:28AM - 25 Aug 21 UTC
I'm currently getting around this limitation by using an ugly hack
```zig
coā¦ nst build_option_file = std.fmt.allocPrint(exe.builder.allocator, "zig-cache/{s}_build_options.zig", .{exe.name}) catch unreachable;
const git_pkg = std.build.Pkg{
.name = "git",
.path = .{ .path = prefix_path ++ "src/git.zig" },
.dependencies = &[_]std.build.Pkg{
.{ .name = "build_options", .path = .{ .path = build_option_file } },
},
};
```
this will fix #5375
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!
cnx
April 14, 2022, 12:40am
4
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.
3 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?
cnx
April 25, 2022, 3:38pm
8
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
For future generations:
Options apply to the module, not the executable.
In the provided example module is declared implicitly.
Written as of zig 0.14.0.
1 Like