This tutorial will guide you through the steps of creating a minimal Zig program that integrates with C++ to print "Hello, World" to the console. This setup will help you understand the basics of combining Zig and C++.
Ensure your project structure looks like this:
simple_hello/ ├── build.zig ├── src/ │ ├── main.zig │ ├── main.cpp │ └── main.h
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(); }
main.cpp
Create the main.cpp
file with the following content:
#include <iostream> #include "main.h" void cppHelloWorld() { std::cout << "Hello, World" << std::endl; }
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
build.zig
Create 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++"); 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, printing "Hello, World" to the console.