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.
By default, the compiler does not warn about unused variables. Use -Wunused-variable to enable this warning specifically, or use an encompassing -W value such as -Weverything . The __attribute__((unused)) attribute can be used to warn about most unused variables, but suppress warnings for a specific set of variables.
To suppress the warning, one can simply name the variable with an underscore ('_') alone. Python treats it as an unused variable and ignores it without giving the warning message.
No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.
Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.
(void) variable
might work for some compilers.
For C++ code, also see 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 Mailbag: Shutting up compiler warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With