Header H or "Zig" entry point?

Good morning,

can we make a direct entry point with a Zig source with a lib that has a .h header

What I would like to do is completely substitute myself and make a direct link.

Could you, perhaps, rephrase your question?
I suspect that the lack of answers is due to people not understanding it.


is it possible to do without the .h to have access to a lib.so written in C language

If I understand what you are asking, you want to directly link to a shared object without including the header file?

edited: The following is incorrect for the zig build system and C code (maybe true for C++) – see @permutationlock’s answer.

I don't believe you can - headers contain declarations that are going to link you up to the shared object files. Maybe someone can show us an example otherwise, but it's apparently a non-trivial task (especially for C++, because it mangles names). I can't speak for the C side of things, so maybe someone can speak to that.

1 Like

If I am understanding correctly, you just want to link against a C library without having to include a C h file? If so, then this is both possible and recommended I believe.

You can use zig translate-c to translate the C header file into Zig. Usually one would then modify the translated header file to remove anything unnecessary (translate-c adds a bunch of boilerplate) and make the pointer types more specific (e.g. change [*c] to be a single or multi-item pointer depending on use case). This is essentially what @cImport is doing anyway. You could also skip translating and manually write the function and type definitions yourself in Zig if you want. The Zig standard library for example has definitions for linking against libc.

Okay, so for the C-translation, if someone doesn’t want to use @cImport, they can translate a file over and link against that (by either rewriting the declarations or by using the output of the translation).

So in some sense, we can’t get away from the linking conventions entirely - that’s still a pretty good deal either way.

Do you know if the same thing is true for C++ code?

1 Like

I haven’t tried linking against C++ yet, but I imagine that it would be a lot more work due to both name mangling (as you mentioned) and the fact that a lot of C++ library APIs are going to use more complicated types that aren’t trivial to translate. I also don’t believe that translate-c works for C++

Interesting stuff - good to know. I was reading stuff from the C build system based on using headers but I didn’t check on the translate-c option in the Zig build system - edited original response.

C++ doesn’t have a stable ABI so calling a C++ function that was compiled with a different frontend than what Zig uses might (will?) result in delicious and subtle bugs.

Linking against C ABI however can be done directly without even seeing the header file - noone told us we cannot stub out the interface directly in Zig on our own, right?