"unused parameter" warnings in C
What's the best way to suppress unused parameter warning in C code.
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.
It gives me 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 after the parameter. For example
auto lambda = [](workerid_t workerId) -> void { };
becomes
auto lambda = [](__attribute__((unused)) _workerid_t workerId) -> void { } ;
You can use gcc/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, in these cases I fall back to (void)coords;
下一篇: C中的“未使用的参数”警告