Can a source file implicit struct be a packed struct?

The documentation states here that zig source files are implicitly structs, as if every file is contained in its own struct { ... } block.

However, I have a project that heavily relies on packed structs, since I’m using such structs to map registers in microcontrollers. Currently, my project looks like this:

As of right now, I have to declare a packed struct Flash inside the flash.zig file and then import that struct instead of just importing the file.

However, what I’d really like to do would be to make the entire flash.zig file the struct definition and then import that in the hal.zig file to declare the register.

So that is my question, can I make the implicit struct from a zig source file packed?

1 Like

see packed vs extern clarification

and Clarification about packed structs

looks like you want to use extern with align

see example

and don’t worry - you are not alone
i also failed in similar case :joy:

4 Likes

welcome to ziggit. @g41797 has linked to some good resources. I’d add that the answer is no. File Structs can’t be marked as packed or extern. they are Plain Old Zig Stucts (POZSs?)

5 Likes

Actually, I really do want to use packed structs, as I’m mapping my registers as bitfields, so I need them bitpacked rather than bytepacked.

But damn, I think my code would be much more readable if I could write it like this:

const Flash = @import("flash.zig");

Is it too niche and specific to my use case or would it be valid to open a Feature Request in the zig repo?

I honestly see these bitfields as one of Zig’s superpowers, since I work with embedded systems daily and they make mapping registers so much easier, so this would be the cherry on top of it, making it perfect.

A very similiar proposal has already been rejected:

2 Likes

Damn, that’s too bad

But I do see the point made at the end of that discussion that however it was implemented the syntax would look worse than to simply write:

const Foo = @import("foo.zig).Foo

Thanks anyways everyone!

3 Likes