Norcroft C sizeof()
Andy Vawer (5817) 28 posts |
Hi folks. I am trying to port some BSD C code over to RISC OS and wonder if anyone has a cunning solution to a sizeof() problem I’ve run into? The original code has a definition along the lines of The header is present in a chunk of bytes immediately before the payload. The code removes the header as part of its message processing. However, it uses sizeof(struct header) to remove the header. Norcroft helpfully rounds up the structure size to a word boundary giving 16 bytes rather than the desired 14 bytes, so I then lose 2 bytes of payload as well. Does anyone know of a cunning way to obtain the true size of the structure without having to hard code a length elsewhere? A macro to replace sizeof would be fantastic as it would save a lot of manual code inspection (I don’t want 14 byte int32_ts)! Or a pragma that can be set? Many thanks Andy |
Jeffrey Lee (213) 6048 posts |
There’s a __packed struct header { u_int8_t message_name[12]; u_int16_t message_id; }; With GCC/clang, the equivalent would be |
Ronald (387) 195 posts |
}__attribute__((packed)); (placed after the struct definition) Seems to compile without error in GCC4.7.4r5. Tried this because I had the same thing happen with the 14 byte struct for the bmp info header. The (C++) program was OK in Linux and gcc/g++7, maybe later compilers can deal with it? |
Andy Vawer (5817) 28 posts |
__packed does the job perfectly. I was aware that it would pack elements within the structure but hadn’t twigged that it would change the sizeof() result as well. Thanks Jeffrey! |