Simplist way to add in a standalone .c file into the build system?

Let’s say I have a blank project with the standard build.zig file generated with zig init (copied below with the comments and test cases removed.)

Assume I also have a file called simple.c and I want to call some functions in this from main.zig.

From this almost blank starting point, what is the most simple way I can add to build.zig?

Motivation: If I was working with a library, I’d package it as a dependency and import it via zig.build.zon but this feels unnecessarily complicated in this scenario, so I’m wondering if there’s a simple shortcut.

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const mod = b.addModule("ziginit", .{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
    });

    const exe = b.addExecutable(.{
        .name = "ziginit",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{ .name = "ziginit", .module = mod },
            },
        }),
    });

    b.installArtifact(exe);

    const run_step = b.step("run", "Run the app");
    const run_cmd = b.addRunArtifact(exe);
    run_step.dependOn(&run_cmd.step);
    run_cmd.step.dependOn(b.getInstallStep());
}
1 Like

std.Build.Module.addCSourceFile

6 Likes

The following way is very problematic (e.g. there are plans to remove @cImport() (github issue)) but it gets around the need to tell the linker which functions are external so in my mind is also simple.

In build.zig add:

exe.addIncludePath(b.path(""));

Create a one-line simple.h:

#include "simple.c"

and finally in main.zig add

const cfile = @cImport({
    @cInclude("simple.h");
});

C functions can then be called like

const b = cfile.increment(a);

Do note that translate-c at this point may not do so well on C files that are not header files. You can achieve the same in build.zig by using b.addTranslateC.