How to use stb_image.h OR Are there any good zig image processing libs for 0.12.0

I am trying to use stb_image.h in my project. Upon compiling, however, I encounter this issue: stb_image.h does not compile · Issue #17495 · ziglang/zig · GitHub.
The issue then points to a workaround SIGSEGV on a cImport case · Issue #17302 · ziglang/zig · GitHub, but I don’t know how to implement what he said there, as I my knowledge of c basically stops at some memory stuff and hello world.
Another project I found was GitHub - JacobCrabill/zig-stb-image: Zig build of the stb_image library (https://github.com/nothings/stb), but I don’t know how to interpret what he did there, how src/stb_image.c came to be and what the thought processes were. I’d be grateful for either help with the workaround or suggestions for easier to compile zig image libs.

You just need this in stb_image.c:

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

Then in your build.zig you can add this file to the executable like this:

exe.addCSourceFiles(.{.files = &[_][]const u8{"path/to/stb_image.c"}, .flags = .{"-g"}}); // -g adds debug info, makes it easier to debug
2 Likes

What file do I then include in my main.zig? / what modifications do I do to it

Just

const c = @cImport({
    @cInclude("stb_image.h");
});
1 Like

IT WORKS, you magic man

For some reason the #define STB_IMAGE_IMPLEMENTATION in main.zig breaks it, strange

Have you by any chance done learnopengl yourself? You know all the answers lol

1 Like

The difference is that @cImport actually tries to translate the c code to zig.
Now the define basically uncomments the implementation code which is more difficult to translate. That’s why it breaks here.
By putting it into a separate C file Zig instead compiles it as C code directly without translating it.

3 Likes

stb_image.c was deprecated 10 years ago:

I don’t think it is safe to use.

I think the suggestion was to add those two lines to your own stb_image.c file. Those two lines will then make that file contain the actual implementation of the functions.

3 Likes

Right. Thanks and sorry for the confusion

1 Like