#Disabling Code with Build Configuration?

1 messages · Page 1 of 1 (latest)

gilded wagon
#

I've been reading up on Zig and am considering trying it out for my next project. One of the things I've had trouble finding good documentation for is how I would do build configurations. Say I had a game and I wanted to create a demo build where some code from the main game was removed. In C++ I can do

#ifndef DEMO_BUILD
void some_function_that_isnt_in_the_demo()
{
    // ...
}
#endif

and then build with a DEMO_BUILD command line argument.

Is there any way to do this for whole blocks or files in Zig?

grim gale
#

well, there aren't macros in zig

#

so it kind of has to be done in units of code

#

you can do stuff like this:

fn some_function_that_isnt_in_the_demo() void {
    if (comptime !demo_build) return; // code after this point is eliminated at compile time if this return is reached
    // code ...
}
#

or you can wrap it if (comptime demo_build) { <code...> }

#

same effect either way

#

you can also do stuff like

const some_function_that_isnt_in_the_demo = if (demo_build) dummyFn else some_function_that_isnt_in_the_demo;
inline fn dummyFn() void {}
fn some_function_that_isnt_in_the_demo_impl() void {
    // code ...
}

at global scope. Does effectively the same thing, just the compile-time semantics are a bit different, namely that in the demo build, dummyFn is always inlined, so it's a guarantee against the some_function_that_isnt_in_the_demo symbol being generated in the executable

junior wren
grim gale
#

beat me to it, but I'll paste what I had:
if you want to know how to make configuration variables, usually that's done in the build system:

    const build_options = b.addOptions();
    build_options.addOption(bool, "foo", false); // hard-coded
    const demo_build = b.option(bool, "demo-build", "Build the demo") orelse false; // requested from the command line as `-Ddemo-build`, defaults to `false`
    build_options.addOption(bool, "demo_build", demo_build);
    exe.addOptions("build-options", build_options); // imported in `exe` as `@import("build-options")`
#

then you could const build_options = @import("build-options"); _ = build_options.foo;

gilded wagon
#

Hm, would that work for enabling/stripping out something like a member function in a struct?

#

And could you do it for multiple functions/structs/etc. in a single statement? I'm guessing the if (comptime ...) can't live in global scope alone, right?

#

Curious if there's a way to do it with less boilerplate when you have multiple functions you want to control at once.