Zig equivalent of gcc used attribute

i need to a force an interrupt handler function to remain in the compiled output – even though it appears not to be used… the function itself is marked export within its container module, where it is being referenced by a C-based interrupt vector table…

here’s the tricky part: i have ModA which imports ModB – where ModB itself contains the exported interrupt handler function…

while my current program directly/indirectly imports ModA, none of its functions are called… as a consequence, ModB effectively disappears from the final executable… other than ModA, no one else has imported ModB

one approach sometimes used with interrupt handlers is to define so-called “weak” symbols, which would allow me to have a default handler for any not explicitly surviving in the final image…

does zig have “weak” definitions??? or does zig have an equivalent to the gcc “used attribute” ???

maybe you are looking for that :slight_smile:

https://ziglang.org/documentation/master/std/#std.mem.doNotOptimizeAway

3 Likes

i would up using “weak” functions in my C code (where my interrupt vector is currently initialized)…

doNotOptimizeAway undoubtedly will prove useful in other scenarios…

in the meanwhile, is there a zig equivalent of “weak” references???

If I understand what you are looking for here, you want something that has a default definition that can be overwritten at some other point if you choose to implement it (aka, there’s a name collision).

There are… analogous… things. In the master std file there is a thing called “options”. It first checks if the root has it declared and if not will provide a default implementation… you can see it here: zig/lib/std/std.zig at master · ziglang/zig · GitHub

In terms of having a symbol defined somewhere that you can overwrite in the case of a name collision, I can’t think of one at the moment. I don’t even believe that weak symbols are mentioned in the c standard either.

I’m sure with enough elbow grease, you can make your import structure turing complete though, lol.

wikipedia has a nice summary…

and while it is NOT part of the standard, i haven’t encountered a C compiler (gcc, clang, iar, keil, …) that doesn’t have support in their linker…

in my case, i little amount of “C glue” contain weak symbols and their defaults goes a long way… in fact, my actual interrupt routines (as well as the default handler) are written as zig export pub functions…

Yes

comptime {
    @export(zigDeclarationToExport, .{ .name = "symbol_name", .linkage = .weak });
}
5 Likes

c++ requires them. The “inline” keyword hasn’t meant inline for years and now basically creates weak symbols (because of the One Definition Rule and how it interacts with header files).

1 Like