How to use `build.zig` to build C++ code

I am trying to build a C++ hello world using zig. Here is what I tried:

// build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "exeCxx",
        .root_source_file = .{ .path = "hello.cxx" },
        .link_libc = true,
    });
    b.installArtifact(exe);
}
// hello.cxx
#include <iostream>
int main (int argc, char *argv[]) {
    std::cout << "Hello, from C++" << std::endl;
    return 0;
}

If I run zig build I get:
fatal error: 'iostream' file not found
How can I link against the C++ stdlib?

You’re apparently missing a exe.linkLibCpp(); in build.zig.

1 Like

Thanks, the following works for me:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const exe = b.addExecutable(.{
        .name = "exeCxx",
        .root_source_file = .{ .path = "hello.cxx" },
    });
    exe.linkLibCpp();
    b.installArtifact(exe);

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

Is there a reason, why I can pass .link_libc = true as an option to b.addExecutable, but not for C++?