#Conditional compilation

1 messages · Page 1 of 1 (latest)

lunar kite
#

I want to add an optional GUI to my app. How can I conditionally compile the GUI file and its corresponding start function in the main file?

oak venture
#

have a build option in your build.zig
import a module with that option into your code
test the option, since it's comptime-known the untaken branches won't be compiled in

#
const std = @import("std");

pub fn build(b: *std.Build) void {
    // (1)
    const opt_color: ?bool = b.option(bool, "color", "use color codes?");
    const opt_message: ?[]const u8 = b.option([]const u8, "message", "set custom message");

    // (2)
    const opts = b.addOptions();

    // (3)
    opts.addOption(bool, "colors", opt_color orelse false);
    opts.addOption(?[]const u8, "msg", opt_message);

    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "hello",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    // (4)
    exe.root_module.addImport("build_options", opts.createModule());

    b.installArtifact(exe);
}

minimal build.zig with some options,

  1. b.option() adds an option to 'zig build --help'. It takes a type, name, and description. This is the outward-facing option.
  2. b.addOptions() creates a std.Build.Step.Options to manage options to be added to build artifacts as an @import()able module.
  3. .addOption adds an option to std.Build.Step.Options. It takes a type, name, and value. This is the inward-facing option, that the artifact actually uses.
  4. This line adds the options as a Zig module to the given artifact, to be imported with the given name (here: build_options).