Minimal Zig Program with C++ and Qt Integration

This tutorial will guide you through the steps of creating a minimal Zig program that integrates with C++ and Qt to create a simple application with a button that says "Hello, World!".

Project Initialization

First, initialize your Zig project:

mkdir simple_hello
cd simple_hello
zig init
        

This will create a basic project structure for you.

Project Structure

Ensure your project structure looks like this:

simple_hello/
├── build.zig
├── src/
│   ├── main.zig
│   ├── main.cpp
│   └── main.h
        

Step 1: Create main.zig

Create the main.zig file with the following content:

const std = @import("std");

extern fn cppHelloWorld() void;

pub fn main() void {
    // Call the C++ function
    cppHelloWorld();
}
        

Step 2: Create main.cpp

Create the main.cpp file with the following content:

#include <QApplication>
#include <QPushButton>
#include "main.h"

void cppHelloWorld() {
    int argc = 0;
    char *argv[] = { nullptr };
    QApplication app(argc, argv);

    QPushButton button("Hello, World!");
    button.resize(200, 100);
    button.show();

    app.exec();
}
        

Step 3: Create main.h

Create the main.h file with the following content:

#ifndef MAIN_H
#define MAIN_H

#ifdef __cplusplus
extern "C" {
#endif

void cppHelloWorld();

#ifdef __cplusplus
}
#endif

#endif // MAIN_H
        

Step 4: Update build.zig

Update the build.zig file with the following content:

const std = @import("std");

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

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

    exe.addCSourceFile(.{
        .file = b.path("src/main.cpp"),
        .flags = &[_][]const u8{
            "-I.",
            "-fPIC",
        },
    });

    exe.addIncludePath(b.path("src")); // Add include path for headers

    exe.linkSystemLibrary("stdc++");
    exe.linkSystemLibrary("Qt5Core");
    exe.linkSystemLibrary("Qt5Widgets");

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

Build and Run

  1. Navigate to your project directory:
    cd /path/to/simple_hello
                    
  2. Build the project:
    zig build
                    
  3. Run the executable:
    zig-out/bin/simple_hello
                    

This setup should compile and run, displaying a window with a button that says "Hello, World!".