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!".
First, initialize your Zig project:
mkdir simple_hello
cd simple_hello
zig init
This will create a basic project structure for you.
Ensure your project structure looks like this:
simple_hello/
├── build.zig
├── src/
│ ├── main.zig
│ ├── main.cpp
│ └── main.h
main.zigCreate 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();
}
main.cppCreate 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();
}
main.hCreate 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
build.zigUpdate 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);
}
cd /path/to/simple_hello
zig build
zig-out/bin/simple_hello
This setup should compile and run, displaying a window with a button that says "Hello, World!".