Re: (void)foo or __unused foo ?

From: Dimitry Andric <dim_at_FreeBSD.org>
Date: Fri, 27 Jul 2012 12:10:29 +0200
On 2012-07-27 11:38, Luigi Rizzo wrote:
> In writing cross platform code I often have to deal with function
> arguments or variables that are not used on certain platforms.
> In FreeBSD:sys/cdefs.h we have
> 
> 	#define __unused        __attribute__((__unused__))
> 
> and in the kernel we tend to annotate with "__unused" such arguments
> 
> 	int f(type foo __unused)
> 
> However on linux __unused is not a standard macro, and is often
> used as a variable or field name in standard headers, so introducing
> our __unused macro breaks compilation there.

Hm, Linux seems to use __unused for padding in structs, and as the name
(!!) of unused parameters in prototypes. :(  It uses the following for
unused attributes:

#define __maybe_unused                  __attribute__((unused))
#define __always_unused                 __attribute__((unused))

The former seems to be used much more throughout the Linux sources, I
count 243 instances of it in my copy, as opposed to just 9 of the
latter.  I don't really understand the rationale (if any) for two
different defines, though.


> The alternative way to avoid an 'unused' warning from the compiler
> is an empty statement
> 
> 	(void)foo;
> 
> that the compiler hopefully optimizes away.
> 
> Any disadvantage or objection to selectively use this form
> in our kernel code for parts that need to work on multiple
> platforms ?

Better to just define a UNUSED_ARG() macro for this, that does the cast.
This will save you having to go over every file again, should you ever
encounter a compiler that complains about useless casts to void...  Then
again, whatever macro name we come up with, might also clash with Linux.

I'm afraid there is no good portable solution, except possibly
undefining __unused just before including Linux headers, then
re-defining it, but that is rather ugly.

Otherwise, either Linux renames all their __unused instances, or we
rename all of them.  Alternatively, we can introduce an __unused2 macro,
just as ugly as the __dead2 and __pure2 macros.  Then replace __unused
with __unused2 in the files that you intend to port to Linux.
Received on Fri Jul 27 2012 - 08:10:29 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:40:29 UTC