#build.zig problem

1 messages · Page 1 of 1 (latest)

royal sorrel
#

I am having problems creating a build.zig

Three files alice.zig, grace.c & bob.zig. Easy to create alice.exe from the command line.

$ zig build-lib bob.zig
$ zig build-exe alice.zig grace.c bob.lib
$ ./alice.exe 
debug: answer is: 42

The problem I have is how to create a single build.zig that builds bob.lib and then builds alice.exe. I cannot work out how to "glue" the lib to the exe.

// alice.zig
const std = @import("std");
pub extern fn grace_c_func(value: c_int) callconv(.C) c_int;

pub fn main() !void {
    std.log.debug("answer is: {d}", .{grace_c_func(21)});
}
// grace.c
extern int bob_zig_func(int value);

int grace_c_func(int value) {
  return bob_zig_func(value);
}
// bob.zig
pub export fn bob_zig_func(value: c_int) callconv(.C) c_int {
    return 2 * value;
}
// build.zig
const std = @import("std");

pub fn build(b: *std.build.Builder) void {
    const target = b.standardTargetOptions(.{});
    const mode = b.standardReleaseOptions();

    const lib = b.addStaticLibrary("bob", "bob.zig");
    lib.setBuildMode(mode);
    lib.install();

    const exe = b.addExecutable("scenario", "alice.zig");
    exe.addCSourceFile("grace.c", &[_][]const u8{});

    // How to glue Exe & Lib ?
    // // exe.addLibraryPath("zig-out/lib/bob.lib");

    exe.setTarget(target);
    exe.setBuildMode(mode);
    exe.install();

    const run_cmd = exe.run();
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}
upbeat grove
#

exe.step.dependOn(lib.step)

#

Combined with exe.linkLibrary

#

Oh wait you might not even need the first one

#

Just exe.linkLibrary(lib) should work

#

Though I do question why you're doing this?

royal sorrel
#

@upbeat grove thanks, obvious when you know how.

#

@upbeat grove to answer your question there is more than one exe that uses the the code in lib.

#

The rest of the answer is that only zig and C knowledge is required. Goodbye CMake.

upbeat grove
#

Hm I guess it could be a little faster to build a static lib and then link it multiple times, rather than importing the zig file in each exe