Using Zig build system for a C++ project

I know it’s kind of a repost, but the only topic I found isn’t useful as the code is out dated.
I would like to have a build.zig file to compile my C++ project, however the compiler telling me, that the I have an invalid token in my code:

src\main.cpp:1:1: error: expected type expression, found 'invalid token'
#include <iostream>
^~~~~~~~~~~~~~~~~~~

Here is my build.zig file that I altered from zig init

const std = @import("std");

pub fn build(b: *std.Build) void {

    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const lib = b.addStaticLibrary(.{
        .name = "directx",
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
    });

    b.installArtifact(lib);

    const exe = b.addExecutable(.{
        .name = "directx",
        .root_source_file = b.path("src/main.cpp"),
        .target = target,
        .optimize = optimize,
    });

    exe.linkLibCpp();

    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);

    const lib_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);

    const exe_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_lib_unit_tests.step);
    test_step.dependOn(&run_exe_unit_tests.step);
}

Can’t find any good source on how to do this.

Hello @XenoBen

addExecutable expects a zig source file for .root_source_file.
You can use addCSourceFile to add a C++ source file; if you don’t have zig files omit .root_source_file or set it to null.

    const exe = b.addExecutable(.{
        .name = "directx",
        .root_source_file = null,
        .target = target,
        .optimize = optimize,
    });
    exe.addCSourceFile(.{
        .file = b.path("src/main.cpp"),
    });
    exe.linkLibCpp();
    exe.linkLibC();

Besides linkLibCpp you might also need linkLibC.

From Build System Tricks, part III. C Dependencies might be of interest to you.

Welcome to ziggit :slight_smile:

3 Likes

It works!

Thank you very much.

I’m happy to be here.

2 Likes

According to the Documentation you linked, I should be able to link directx libs and compile them aswell, right?

You can build and link libraries in general, yes.