#Zig.build for C project

1 messages · Page 1 of 1 (latest)

trim relic
#

Hello, I'm trying out using zig for building a C project. Is this a good way to make the build.zig for a C project?

const std = @import("std");

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

    const exe = b.addExecutable(.{
        .name = "hello",
        .root_module = b.createModule(.{
            .target = target,
            .optimize = optimize,
        }),
    });

    exe.addCSourceFile(.{
        .file = b.path("main.c"),
        .flags = &[_][]const u8{ "-std=c11", "-Wall", "-Wextra", "-Werror" },
    });

    exe.linkLibC();

    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    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);
}
cold wagon
#

u should do things like adding c source files and linking libc through the module, rather than the exe step. ie:

const mod = b.createModule(.{
    .target = target,
    .optimize = optimize,
    .link_libc = true,
});

mod.addCSourceFile(.{
    .file = b.path("main.c"),
    .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" },
});

const exe = b.addExecutable(.{
    .name = "hello",
    .root_module = mod,
});
#

(going through the exe step is deprecated)

#

other than that tho, looks fine to me :)

#

tho u may find addCSourceFiles more useful than addCSourceFile, since most C projects have more than one source file ^-^

trim relic
#

if you do files and start adding more files what would that look like? another .file entry?

cold wagon
#

it takes a slice of filenames :)

#

so eg. ```ts
mod.addCSourceFiles(.{
.files = &.{ "main.c", "my_super_cool_code.c" },
.flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" },
});

trim relic
#

Awesome tysm for the help! 2 more questions if you wouldn't mind?
How are you getting syntax highlighting in your discord code blocks?

second question could you explain the syntax difference here?

.flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" },

.flags = &[_][]const u8{ "-std=c11", "-Wall", "-Wextra", "-Werror" },
gentle moth
#

People usually use rs or ts to get highlighting on Discord. If you right click and copy the text you can see how people acheive whatever formatting in Discord markdown.

cold wagon
cold wagon
#

u can think of the . in .{ ... } as saying "infer the type from context"