Kallo
Kallo

Reputation: 45

Need help using a C library in zig

I am trying to port the microUI library from C into zig.

I have tried using this port attempt https://gitdab.com/luna/zig-microui as a guide post, but it does not seem to work.

Here is a breakdown of my attempt so far:

MicroUI is a very simple program, consisting of one .h file and one .c file. both of these files are located in the root of my project under the folder "./microui".

My build.zig:

const std = @import("std");

const c_args = [_][]const u8{
    "-Wall",
    "-std=c11",
    "-pedantic",
    // prevent sigill
    "-fno-sanitize=undefined",
};

pub fn build(b: *std.build.Builder) void {
    // Standard release options allow the person running `zig build` to select
    // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
    const mode = b.standardReleaseOptions();

    const lib = b.addStaticLibrary("ZigMicroUI", "src/main.zig");
    lib.linkSystemLibrary("c");
    lib.linkLibC();
    lib.addIncludeDir("./microui");
    lib.addCSourceFile("microui/microui.c", &c_args);

    lib.setBuildMode(mode);
    lib.install();

    var main_tests = b.addTest("src/main.zig");
    main_tests.setBuildMode(mode);

    const test_step = b.step("test", "Run library tests");
    test_step.dependOn(&main_tests.step);
}

c.zig:

pub usingnamespace @cImport({
    @cInclude("microui.h");
});

Relevant part of main.zig:

const std = @import("std");
const testing = std.testing;
const c = @import("c.zig");

export fn begin_window() void {
   const ctx: c.mu_Context = null;
}

Output from 'zig build test':

.\src\c.zig:1:20: error: C import failed
pub usingnamespace @cImport({
                   ^
.\src\c.zig:1:20: note: libc headers not available; compilation does not link against libc
pub usingnamespace @cImport({
                   ^
.\zig-cache\o\013eb3e1efd6fe219480e321f33592ae\cimport.h:1:10: note: 'microui.h' file not found
#include <microui.h>
         ^
.\src\main.zig:6:16: error: container 'c' has no member called 'mu_Context'
   const ctx: c.mu_Context = null;

I feel like this has to be something small that I'm missing if anyone can help.

Upvotes: 2

Views: 4717

Answers (1)

solarc
solarc

Reputation: 5738

You have to add the configuration to main_tests too:

main_tests.linkLibC();
main_tests.addIncludeDir("microui");
main_tests.addCSourceFile("microui/microui.c", &c_args);

Then zig build test will work.

Upvotes: 3

Related Questions