ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
32.76k stars 2.38k forks source link

expected type 'T', found 'T' with different cImport #19420

Closed arthurmelton closed 4 months ago

arthurmelton commented 4 months ago

Zig Version

0.12.0-dev.3435+091aa54a3

Steps to Reproduce and Observed Behavior

You can get this error by compiling the following:

const c_one = @cImport({
    @cInclude("adwaita.h");
    @cInclude("gtk/gtk.h");
});

pub var layout_list: ?*c_one.GtkStringList = null;

const c_two = @cImport(@cInclude("gtk/gtk.h")); // could be in different file

pub fn main() void {
    layout_list = c_two.gtk_string_list_new(null); // could be in different file
}

then build with zig build-exe main.zig -lc $(pkg-config --cflags-only-I gtk4 libadwaita-1)

The output from compiling is the following:

main.zig:11:44: error: expected type '?*cimport.struct__GtkStringList', found '?*cimport.struct__GtkStringList'
    layout_list = c_two.gtk_string_list_new(null);
                  ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
main.zig:11:44: note: pointer type child 'cimport.struct__GtkStringList' cannot cast into pointer type child 'cimport.struct__GtkStringList'
.cache/zig/o/4eaa1196051a3c1d58c87fe72382fb3a/cimport.zig:48670:35: note: opaque declared here
pub const struct__GtkStringList = opaque {};
                                  ^~~~~~~~~
.cache/zig/o/81f98775d68e386e5e954b54f8336c55/cimport.zig:48670:35: note: opaque declared here
pub const struct__GtkStringList = opaque {};
                                  ^~~~~~~~~

Expected Behavior

I don't know exactly what is causing the problem, but I don't think adwaita.h is overwriting the struct. The code does work if you either add adwaita.h to the other import, or remove adwaita.h from the first import. If the struct is being overwritten, then maybe the error should try to express that.

This was as minimal as I could get the code, as I have no idea what in particular it is upset about.

Vexu commented 4 months ago

Duplicate of #12073

Each @cImport causes the file to be translated again creating new, distinct types. This is why it is advisable to only have one @cImport in your project. See the documentation here https://ziglang.org/documentation/master/#cImport.

Related https://github.com/ziglang/zig/issues/4017