A better way to deal with gcc's 'strict aliasing' warning

Alejandro Mery amery at geeks.cl
Mon Dec 15 23:45:18 CET 2014



On 30.07.2012 12:04, Jianbin Kang wrote:
> Hello,
>
>         In `ev.h', the macro using (type of ev_watch *)(void *)(ev) to
> convert `ev' to a required type.
>         The (void *) conversion may be used to supress gcc's 'strict
> aliasing' warning (not sure).
>         This may work in previous version of gcc, but failed with gcc 4.7:
>                   warning: dereferencing type-punned pointer will break
> strict-aliasing rules [-Wstrict-aliasing]
>
>        The better way is to put all ev_watch type to an union (such as
> union ev_any_watcher in "ev.h"),
>        and convert the pointer to (union ev_any_watch *).
>        For example, the following code can supress strict-aliasing
> warning for macro 'ev_init':
>               typedef ev_any_watcher ev_any;
>               #define ev_init(ev,cb_) do {                    \
>                 ((ev_any *)(ev))->w.active  =                \
>                 ((ev_any *)(ev))->w.pending = 0;         \
>                 ev_set_priority ((ev), 0);                      \
>                 ev_set_cb ((ev), cb_);                         \
>              } while (0)
>             # define ev_set_priority(ev,pri)             (   (ev_any
> *)(ev))->w.priority = (pri)
>
>
>        Is there any suggestion?

I usually reimplement ev_foo_init() macros the as static inline 
functions with explicit types, and then everything goes smoothly.



More information about the libev mailing list