I just saw this
Build mix cpp and zig code - Help - Ziggit
Can I use zig to build my C++ code and unit test it from zig as long as the include files, in the C++ file, only is a simple C header file?
Yes, you can.
Yes, you can call functions using C ABI (callable by C using extern “C” ).
I’ve used catchorg/Catch2
to test C/C++ codes.
Following is a Zig side code:
const std = @import("std");
extern fn run_catch2_test(test_report_path: [*c]const u8) callconv(.C) c_int;
const TEST_OUTPUT: [:0]const u8 = "test_result.txt";
pub fn run_catch2(allocator: std.mem.Allocator) !c_int {
const err = run_catch2_test(TEST_OUTPUT);
if (err > 0) {
const file = try std.fs.cwd().openFile(TEST_OUTPUT, .{});
defer file.close();
const meta = try file.metadata();
const data = try file.readToEndAlloc(allocator, meta.size());
defer allocator.free(data);
std.debug.print("Catch2 output:\n{s}\n", .{data});
}
return err;
}
Following is a C code:
#include <catch2/catch_session.hpp>
#include <iostream>
#include <fstream>
extern "C" {
auto run_catch2_test(const char *redirect_path) -> int {
std::ofstream out(redirect_path);
std::streambuf* coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
int argc = 1;
const char* argv[] = { "your_program_name" };
Catch::Session session;
session.applyCommandLine(argc, argv);
auto result = session.run();
std::cout.rdbuf(coutbuf);
return result;
}
}
EDIT: I’ve dump to textfile in C-side to print the textfile in Zig-side because Zig locks stdout