#Importing C++ code as C

1 messages · Page 1 of 1 (latest)

sour peak
#

I'm trying to include dear imgui in my project straight from the repo. Here's my build code

    exe.addIncludePath(b.path("external/imgui"));
    exe.addIncludePath(b.path("external/imgui/backends"));
    exe.addCSourceFiles(.{
        .root = b.path("external/imgui"),
        .flags = &.{"-std=c++11"},
        .files = &[_][]const u8{
            "imgui.cpp",
            "imgui_draw.cpp",
            "imgui_tables.cpp",
            "imgui_widgets.cpp",
            "backends/imgui_impl_sdl3.cpp",
            "backends/imgui_impl_sdlgpu3.cpp",
        },
    });

    exe.linkLibCpp();

But when I try to include the headers

pub const imgui = @cImport({
    @cInclude("imgui.h");
    @cInclude("imgui_impl_sdl3.h");
    @cInclude("imgui_impl_sdlgpu3.h");
});

I see errors that make it look like it's trying to use this as C, not C++ code

Diagnostics:
1. C import failed
2. must use 'struct' tag to refer to type 'ImGuiInputTextCallbackData'
3. must use 'struct' tag to refer to type 'ImGuiSizeCallbackData'
4. unknown type name 'constexpr'
5. call to undeclared function 'x'; ISO C99 and later do not support implicit function declarations
6. expected parameter declarator
7. expected ')'
8. duplicate member 'y'
9. expected ';' at end of declaration list

I thought that by adding .flags = &.{"-std=c++11"}, it would force this code to be built as c++, but maybe I'm missing something here

late panther
#

c++ works in addCSourceFiles, but not in translate-c (which is used in @cImport).

dim flower
#

you can use cimgui, one of the existing Zig bindings for imgui, or use a different immediate mode UI lib, like nuklear :)

sour peak
dim flower
#

you wrap them in a C API

#

which is what cimgui does for imgui

#

so you can use that to avoid writing your own C API for it

sour peak
#

Thanks. For my own understanding, could I also write a Zig API using extern statements and have that work?

dim flower
#

only if there is a C API to bind to

#

Zig can't interface directly with C++ APIs

sour peak
#

Alright, I think I understand. Are you aware of any online resources that go over this kind of thing? Using C++ code through zig

dim flower
#

there are resources about using C with zig and probably resources about wrapping C++ apis with C ones

#

put the two together and that's what you need :)

#

whether there's a guide for wrapping C++ in C specifically for use with zig, I don't know

sour peak
#

Cool cool, thanks for the help