What does define COMMENT_ONLY mean?

Bruce Evans brde at optusnet.com.au
Sat Jul 23 03:09:11 UTC 2011


On Fri, 22 Jul 2011, Vladimir Budnev wrote:

> What does this define
>
> COMMENT_ONLY
>
> mean and what for it is used?

Try googling the structure hack (I didn't).

> Iv met such one in if_arp.h source in freebsd kernel, but cant get such
> strange if in arp header structure.
>
> -----------------------------------example
> struct  arphdr {
> <...>
> /*
> * The remaining fields are variable in size,
> * according to the sizes above.
> */
> #ifdef COMMENT_ONLY
>        u_char  ar_sha[];       /* sender hardware address */
>        u_char  ar_spa[];       /* sender protocol address */
>        u_char  ar_tha[];       /* target hardware address */
>        u_char  ar_tpa[];       /* target protocol address */
> #endif
> };

C didn't support support variable-sized structs before C99, and
doesn't really support them now.  Various hacks are used to make
pseudo-structs larger or smaller than ones that can actually be
declared work.  The above is one.  The pseudo-struct is malloc()ed
and has size larger than the declared one.  The above says what
would be in it if it could be declared.

If this were written in C99, it might declare u_char ar_foo[] in the
the code instead of in a comment.  But C can't really support variable-
sized structs.  It only allows one ar_foo[], which must be at the end
of the struct.  ar_foo then has a known offset but an unknown size.
The other ar_bar[]'s still can't be declared, since they want to be
further beyond the end of the struct, which places them at an unknown
offset.

A probably-less-unportable way was to declare everything in the struct
but malloc() less.  This only works if all the magic fields are at
known offsets.  This doesn't work in the above, since the fields want
to have variable lengths each and thus end up at variable offsets.
Such fields can be allocated from a single larger field (usually an
an array), but you lose the possibility of declaring them all.

Bruce


More information about the freebsd-net mailing list