I’ve been working on translating a C library’s header into a Zig module so that it is more easily depended upon by Zig consumers.
Aforementioned header contains declarations dependent on a macro definition.
This includes functions, e.g.
#ifdef FOO
void bar(void);
#endif
but it also includes extern
variables:
#ifdef FOO
extern int baz;
#endif
I’ve translated the macro FOO
itself to a build option that I can then import/access in the Zig module, but I haven’t been able to find any resources on how I might comptime
guard the extern
variable declaration/functions on the build option.
Is this possible? Is there any best-practice in wrapping this C-ism in Zig? Any pointers would be much appreciated!
Due to Zig’s conditional compilation, I think you can just have it there without any checking:
extern fn bar() void;
// On access
if(FOO) {
...
bar();
...
} else {
...
}
As long as FOO
is comptime-known false the compiler won’t even compile the code accessing bar
and therefor it will not attempt to link it.
If you want to guard access you can of course still do that with a separate variable:
const guardedBar = if(FOO) &bar else @compilerError("Attempt to access 'bar', but 'FOO' is not set");
1 Like
an alternative to the last, if you dont want bar to exist at all without foo:
const bar = if(FOO) @extern(Type, .{.name = "bar"}) else @compileError("bar not defined without `FOO`");
7 Likes
This seems great, thank you! I didn’t think of using the @extern
builtin instead of the keyword.