zig icon indicating copy to clipboard operation
zig copied to clipboard

zig build: convenience API for setting config variables

Open andrewrk opened this issue 8 years ago • 5 comments

@compileVar currently only gives access to the builtin compile variables - is_release, os, arch, and a couple others.

It should be possible to specify compile variables via the command line, and it should allow more than type bool.

Once we have the zig build system then it should be possible to programmatically add compile variables in the build script.

andrewrk avatar Jan 31 '17 06:01 andrewrk

Compile variables are the same thing as importing a generated .zig file, which inspires this idea:

Instead of @compileVar("name"), have @import("compile_vars").name. Maybe we make a special name for zig compile vars such as @import("@config").

This solves #220 as well. Instead of @Os it would be @import("@config").Os.

Then for user compile variables we need a way to specify packages on the command line, which we already want, something like -Ppkg_name=path/to/index.zig. So then if you wanted to pass compile variables to zig code, you put them in e.g. config.zig and then do zig build_exe main.zig -Pconfig=config.zig, and then import them with @import("config"). Example config.zig:

pub const include_horse_galloping_feature = false;
pub const default_allocator = @import("std").mem.IncrementingAllocator.init(10 * 1024 * 1024);

Now the only thing left is to add compile variables in the build script. For this we can provide an API that has an interface roughly like this:

const exe = b.addExe("app", "app.zig");
const config = b.addConfig();
config.add("include_horse_galloping_feature", false);
config.add("number_of_things", b.option("number-of-things", u32, "Set the number of things"));
config.add("name", "blah blah");
exe.addConfig("config", config);

This would generate config.zig and then pass the -Pconfig=config.zig parameter when building. Of course it's not necessary to use this API; you could alternately provide or write your own .zig file and then use the API to add a package directly.

andrewrk avatar May 01 '17 05:05 andrewrk

We have exe.addBuildOption but it creates a global "build_options" package to import. The API I described in the comment above would be better. I'm going to put this issue in the category of "zig package manager issues" (#943).

andrewrk avatar Feb 22 '19 14:02 andrewrk

I gave this a try:

module.addBuildOption([]const u8, "basename", "stub");

resulted in:

pub const basename = stub;

which is obviously incorrect...

daurnimator avatar Nov 24 '19 03:11 daurnimator

Is this resolved by the addition of Builder.addOptions and OptionsStep?

courajs avatar Oct 23 '21 19:10 courajs

It works fine now.

iacore avatar Nov 07 '22 14:11 iacore