What is the best/neatest way to suppress a compiler (in this case gcc) like "Unused variable x"-warning?
I don't want to give any certain flags to gcc to remove all these warnings, just for special cases.
(void) variable
might work for some compilers.
For C++ code, also see http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/ where Herb Sutter recommends using:
template<class T> void ignore( const T& ) { }
...
ignore(variable);
void foo(int /*bar*/) {
...
}
See individual answers for __attribute__((unused))
, various #pragma
s and so on. Optionally, wrap a preprocesor macro around it for portability.
IDEs can signal unused variables visually (different color, or underline). Having that, compiler warning may be rather useless.
In GCC and Clang, add -Wno-unused-parameter
option at the end of the command line (after all options that switch unused parameter warning on, like -Wall
, -Wextra
).
void foo(int bar) {
(void)bar;
}
as per jamesdlin's answer and http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
Found an article http://sourcefrog.net/weblog/software/languages/C/unused.html that explains UNUSED. Interesting that the author also mangles the unused variable name so you can't inadvertently use it in the future.
Excerpt:
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#else
# define UNUSED(x) x
#endif
void dcc_mon_siginfo_handler(int UNUSED(whatsig))
If this is really what you want, you could use the unused attribute (gcc only), something like:
void foo(int __attribute__((__unused__)) bar) {
...
}
Not just for function parameters, of course, but that's the most common use case, since it might be a callback function for an API where you don't actually need all the input.
Additionally, GLib has a G_GNUC_UNUSED macro which I believe expands to that attribute.
The cast to a void is the best approach because it shows that you didn't "accidentally" keep the variable in your code - ie: this function might be an instance where you have a table of function pointers that need the same parameter types and return types, but in this particular table entry you are not using the parameter.
That said, if you don't need it, get rid of it. ;)
Delete the unused variable declaration from the code. (pun intended)
(What??? it's what I do: point that the obvious is most likely the best solution.)
Now, from comments on other answers, apparently it's garbage generated from macros. Well, that's a pleonasm.
Solutions:
void function_name(int par1, char *par2);
and you only need to work on par2. – Residuumvoid function_name(int par1, char*);
which is perfectly valid and won't generate warnings. – Frank Kusterserror: parameter name omitted
. – craig65535