Passing build option to code from the zig command line?

I’m developing my own N-dimensional array library and would like to be able to build it either with Zig-only reference innerloops or with fast SIMD loops written in C.

How can I choose either-or in my array code? I’d like to be able to make this choice at the zig command line level as some kind of a build option. But furthermore, I’d also like to keep zig test src/ndarray.zig working – this currently breaks if I introduce C code into my build.zig.

F.ex., how would I control the value of use_native_c_innerloops below from the Zig commandline?

pub fn gemm(TA: bool, TB: bool, M: usize, N: usize, K: usize, alpha: f32, A: []f32, lda: usize, B: []f32, ldb: usize, beta: f32, C: []f32, ldc: usize) void {
    if (use_native_c_innerloops) {
        const transpose_A: u8 = if (!TA) 'N' else 'T';
        const transpose_B: u8 = if (!TB) 'N' else 'T';

        const Mc: c_int = @intCast(M);
        const Nc: c_int = @intCast(N);
        const Kc: c_int = @intCast(K);

        c.sgemm_sse('R', transpose_A, transpose_B, Mc, Nc, Kc, alpha, A.ptr, @intCast(lda), B.ptr, @intCast(ldb), beta, C.ptr, @intCast(ldc));
        return;
    }
    ... gemm Zig implementation follows
}

In build.zig:

const use_native_c_inner_loops = b.option(bool, "loops", "use native C inner loops") orelse false;
const options = b.addOptions();
options.addOption(bool, "use_native_c_inner_loops", use_native_c_inner_loops);
exe.addOptions("config", options);

Then in your code

const config = @import("config");

if (config.use_native_c_inner_loops) ...

This means that you can do zig build run -Dloops to enagle the feature.

5 Likes

Thanks!

How can I keep using zig test src\ndarray.zig with this pattern?

I realize I can also build my tests with build.zig, but zig test is sometimes handier.