code: bitsizeof() and bitoffsetof()
U.Mutlu
um@mutluit.com
Mon Apr 22 23:44:00 GMT 2019
U.Mutlu wrote on 04/22/2019 11:11 PM:
> Hi,
> is there a way to suppress a gcc compiler warning locally inside a macro code?
>
> #include <stddef.h> // size_t
> #include <strings.h> // ffs()
>
> #define bitsizeof(type, member) \
> ({ type t; \
> t.member = ~0u; /* compiler warning -Woverflow happens */ \
> const size_t rc = ffs(t.member + 1); \
> !rc ? sizeof(unsigned) * 8 : rc - 1; \
> })
>
> The -Woverflow warning happens because the struct member field is
> a small bitfield, for example "unsigned x : 5;".
Solved it with a workaround replacement:
#define bitsizeof(type, member) \
({ struct type t; \
unsigned i = t.member = 1; \
while (t.member <<= 1) \
i = (i << 1) | 1; \
t.member = i; \
const size_t rc = ffs(t.member + 1); \
!rc ? sizeof(unsigned) * 8 : rc - 1; \
})
Attached I've found also a solution for getting the offsetof of bitfields in
structs/classes.
I think these routines are portable regarding wordize, endianness and language
(C, C++).
Tested with gcc/g++ v4.9 on ARM 32bit (armv7-a, arm-linux-gnueabihf) and
x86_64 (x86_64-linux-gnu).
-------------- next part --------------
A non-text attachment was scrubbed...
Name: bitsizeof.h
Type: text/x-chdr
Size: 1756 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20190422/777f2dfa/attachment-0002.bin>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.c
Type: text/x-csrc
Size: 665 bytes
Desc: not available
URL: <https://gcc.gnu.org/pipermail/gcc-help/attachments/20190422/777f2dfa/attachment-0003.bin>
More information about the Gcc-help
mailing list