How can I suppress "unused parameter" warnings in C?
For instance:
Bool NullFunc(const struct timespec *when, const char *who)
{
return TRUE;
}
In C++ I was able to put a /*...*/
comment around the parameters. But not in C of course, where it gives me the error:
error: parameter name omitted
I usually write a macro like this:
#define UNUSED(x) (void)(x)
You can use this macro for all your unused parameters. (Note that this works on any compiler.)
For example:
void f(int x) {
UNUSED(x);
...
}
In GCC, you can label the parameter with the unused
attribute.
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
In practice this is accomplished by putting __attribute__ ((unused))
just before the parameter. For example:
void foo(workerid_t workerId) { }
becomes
void foo(__attribute__((unused)) workerid_t workerId) { }
You can use GCC or Clang's unused attribute. However, I use these macros in a header to avoid having GCC specific attributes all over the source, also having __attribute__
everywhere is a bit verbose/ugly.
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#ifdef __GNUC__
# define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x
#else
# define UNUSED_FUNCTION(x) UNUSED_ ## x
#endif
Then you can do...
void foo(int UNUSED(bar)) { ... }
I prefer this because you get an error if you try use bar
in the code anywhere, so you can't leave the attribute in by mistake.
And for functions...
static void UNUSED_FUNCTION(foo)(int bar) { ... }
Note 1):
As far as I know, MSVC doesn't have an equivalent to __attribute__((__unused__))
.
Note 2):
The UNUSED
macro won't work for arguments which contain parenthesis,
so if you have an argument like float (*coords)[3]
you can't do, float UNUSED((*coords)[3])
or float (*UNUSED(coords))[3]
. This is the only downside to the UNUSED
macro I found so far, and in these cases I fall back to (void)coords;
.