How do I disable Unused Variable warnings in Eclipse in minGW? - c++

How can I disable the following warning in C++ in minGW?
warning: unused variable 'x' [-Wunused-variable]
In Eclipse CDT, I can't locate the warning number:
../src/subfolder/ClassTwo.cpp:20:8: warning: unused variable 'x' [-Wunused-variable]
I tried doing this:
#pragma warning(push)
#pragma warning(disable: ?) //which number?
#include "subfolder/ClassTwo.h"
#pragma warning(pop)
But it didn't work.
My questions:
How can I get the warning number of this in Eclipse CDT?
How should the pragma directive be written?

Since it's NEARLY always easy to fix "unused variable" warnings, I'd very much prefer to fix the actual code than try to patch it up with pragmas (which may hide other, future errors too - for example you add a new function:
int foo(int x, int y)
{
return x * x;
}
Oops, that's a typo, it's supposed to be return x * y; - a warning would give you indication that this is the case.
Unused parameters, as someone mentioned, are dealt with by removing the name of the parameter:
int foo(int x, int) // Second parameter, y is not used
{
return x * x;
}
If it's a local variable, then you can use (void)y (perhaps in aa macro) to "fake use it":
int bar(int x)
{
int y; // Not used.
(void)y;
}
or
#define NOT_USED(x) (void)(x)
int bar(int x)
{
int y; // Not used.
NOT_USED(y);
}

It looks like the output from clang. You can achieve the same using clang using the approach outlined here: http://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
#include "subfolder/ClassTwo.h"
#pragma clang diagnostic pop
If that's your source file, then just fix the warning.
For GCC, you can use this: Selectively disable GCC warnings for only part of a translation unit?
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#include "subfolder/ClassTwo.h"
#pragma GCC diagnostic pop
Of course, that will leave you with a good amount of pragma noise -- debatable if that is a bad thing =)

You seem to be using Microsoft C++ style pragma syntax with GCC compiler. The concept of "warning number" (at least in that format) is also Microsoft C++ specific. In other words, this should not work in GCC.
There's no standard syntax for disabling/enabling warnings, so each compiler will use its own. That means that there's no way to do it "in C++" (quoting your title). There are only ways to do it in each specific compiler. You have to consult your compiler docs for that.
In GCC you should be able to do it through command-line options -Wno-unused-variable do disable all such warnings for the entire translation unit. Also, in GCC you can actually selectively mark variables as unused through __attribute__((unused)) to suppress warnings for that specific variable.
http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html#Variable-Attributes

Related

Exception/exclusion for -Wpadded warning

I have -Wpadded warning option on (gcc/g++) and getting these warnings for non-padded C/C++ structures as expected.
Now, I want to exclude some of the structures from that warning without having to actually pad them.
To make things even more complicated - I have "-Wall". This makes the approach with #pragma GCC diagnostics ignored -Wpadded not usable (shame, would have been very neat).
Some sort of "pragma" directive in the code is what I would expect as a solution. Thanks in advance!
Please note that there was a misspelling in my original question text! Refer to the accepted answer for the confirmation that the method with #pragma actually works!
Yes, GCC has pragmas for this:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpadded"
// Doesn't warn
struct Foo { bool x; int y; };
#pragma GCC diagnostic pop
// Warns
struct Bar { bool x; int y; };
(live demo)
Nothing about -Wall makes this complicated or in any way a problem; you just have to spell the pragma correctly. 😊

How do I make compilation stop nicely if a constant is used in my source file?

I want to test for the use of a constant in a source file and if it is used, stop compilation.
The constant in question is defined in a generic driver file which a number of driver implementations inherit from. However, it's use has been deprecated so subsequent updates to each drivers should switch to using a new method call and not the use of this const value.
This doesn't work obviously
#ifdef CONST_VAR
#error "custom message"
#endif
How can I do this elegantly? As It's an int, I can define CONST_VAR as a string and let it fail, but that might make it difficult for developers to understand what actually went wrong. I was hoping for a nice #error type message.
Any suggestions?
The Poison answer here is excellent. However for older versions of VC++ which don't support [[deprecated]] I found the following works.
Use [[deprecated]] (C++14 compilers) or __declspec(deprecated)
To treat this warning as an error in a compilation unit, put the following pragma near the top of the source file.
#pragma warning(error: 4996)
e.g.
const int __declspec(deprecated) CLEAR_SOURCE = 0;
const int __declspec(deprecated("Use of this constant is deprecated. Use ClearFunc() instead. See: foobar.h"));
AFAIK, there's no standard way to do this, but gcc and clang's preprocessors have #pragma poison which allows you to do just that -- you declare certain preprocessor tokens (identifiers, macros) as poisoned and if they're encountered while preprocessing, compilation aborts.
#define foo
#pragma GCC poison printf sprintf fprintf foo
int main()
{
sprintf(some_string, "hello"); //aborts compilation
foo; //ditto
}
For warnings/errors after preprocessing, you can use C++14's [[deprecated]] attribute, whose warnings you can turn into errors with clang/gcc's -Werror=deprecated-declarations .
int foo [[deprecated]];
[[deprecated]] int bar ();
int main()
{
return bar()+foo;
}
This second approach obviously won't work for on preprocessor macros.

Is it possible to disable warning on specific statements - Warnings treated as errors [duplicate]

Is there a way to disable just a single warning line in a cpp file with visual studio?
For example, if I catch an exception and don't handle it, I get error 4101 (unreferenced local variable). Is there a way to ignore this just in that function, but otherwise report it in the compilation unit? At the moment, I put #pragma warning (disable : 4101) at the top of the file, but that obviously just turns it off for the whole unit.
#pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop )
If you only want to suppress a warning in a single line of code (after preprocessing)[1], you can use the suppress warning specifier:
#pragma warning(suppress: 4101)
// here goes your single line of code where the warning occurs
For a single line of code, this works the same as writing the following:
#pragma warning(push)
#pragma warning(disable: 4101)
// here goes your code where the warning occurs
#pragma warning(pop)
[1] Others have noted in comments below that if the following statement is an #include statement that the #pragma warning(suppress: 4101) statement would not effectively suppress the warning for every line in the header file. If one were intending to do that, one would need to utilize the push/disable/pop method instead.
#pragma push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?
try
{
// ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
// ...
}
Example:
#pragma warning(suppress:0000) // (suppress one error in the next line)
This pragma is valid for C++ starting with Visual Studio 2005.
https://msdn.microsoft.com/en-us/library/2c8f766e(v=vs.80).aspx
The pragma is NOT valid for C# through Visual Studio 2005 through Visual Studio 2015.
Error: "Expected disable or restore".
(I guess they never got around to implementing suppress ...)
https://msdn.microsoft.com/en-us/library/441722ys(v=vs.140).aspx
C# needs a different format. It would look like this (but not work):
#pragma warning suppress 0642 // (suppress one error in the next line)
Instead of suppress, you have to disable and enable:
if (condition)
#pragma warning disable 0642
; // Empty statement HERE provokes Warning: "Possible mistaken empty statement" (CS0642)
#pragma warning restore 0642
else
That is SO ugly, I think it is smarter to just re-style it:
if (condition)
{
// Do nothing (because blah blah blah).
}
else
Use #pragma warning ( push ), then #pragma warning ( disable ), then put your code, then use #pragma warning ( pop ) as described here:
#pragma warning( push )
#pragma warning( disable : WarningCode)
// code with warning
#pragma warning( pop )
as #rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop
this info comes from here
One may also use UNREFERENCED_PARAMETER defined in WinNT.H. The definition is just:
#define UNREFERENCED_PARAMETER(P) (P)
And use it like:
void OnMessage(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
}
Why would you use it, you might argue that you can just omit the variable name itself. Well, there are cases (different project configuration, Debug/Release builds) where the variable might actually be used. In another configuration that variable stands unused (and hence the warning).
Some static code analysis may still give warning for this non-nonsensical statement (wParam;). In that case, you mayuse DBG_UNREFERENCED_PARAMETER which is same as UNREFERENCED_PARAMETER in debug builds, and does P=P in release build.
#define DBG_UNREFERENCED_PARAMETER(P) (P) = (P)
Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.
Although there are some other options, including #pramga warning (once).
This question comes up as one of the top 3 hits for the Google search for "how to suppress -Wunused-result in c++", so I'm adding this answer here since I figured it out and want to help the next person.
In case your warning/error is -Wunused (or one of its sub-errors) or -Wunused -Werror only, the solution is to cast to void:
For -Wunused or one of its sub-errors only1, you can just cast it to void to disable the warning. This should work for any compiler and any IDE for both C and C++.
1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase "All the above -Wunused options combined" and look there for the main -Wunused warning and above it for its sub-warnings. The sub-warnings that -Wunused contains include:
-Wunused-but-set-parameter
-Wunused-but-set-variable
-Wunused-function
-Wunused-label
-Wunused-local-typedefs
-Wunused-parameter
-Wno-unused-result
-Wunused-variable
-Wunused-const-variable
-Wunused-const-variable=n
-Wunused-value
-Wunused = contains all of the above -Wunused options combined
Example of casting to void to suppress this warning:
// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var; // <===== SOLUTION! ======
For C++, this also works on functions which return a variable marked with [[nodiscard]]:
C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)
So, the solution is to cast the function call to void, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]] attribute) to void.
Example:
// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass
{
public:
// fill in class details here
private:
// fill in class details here
};
// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
MyNodiscardClass myNodiscardClass;
return myNodiscardClass;
}
int main(int argc, char *argv[])
{
// THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
// IF YOU HAVE `-Wunused` turned on, since you are
// discarding a "nodiscard" return type by calling this
// function and not using its returned value!
MyFunc();
// This is ok, however, as casing the returned value to
// `void` suppresses this `-Wunused` warning!
(void)MyFunc(); // <===== SOLUTION! ======
}
Lastly, you can also use the C++17 [[maybe_unused]] attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.
If you want to disable unreferenced local variable write in some header
template<class T>
void ignore (const T & ) {}
and use
catch(const Except & excpt) {
ignore(excpt); // No warning
// ...
}
In certain situations you must have a named parameter but you don't use it directly.
For example, I ran into it on VS2010, when 'e' is used only inside a decltype statement, the compiler complains but you must have the named varible e.
All the above non-#pragma suggestions all boil down to just adding a single statement:
bool f(int e)
{
// code not using e
return true;
e; // use without doing anything
}

suppress warnings on multiple compiler builds

Is there a generic suppress warning that i can use?
The problem is that there are times i may build using one compiler version (gcc) and then i have a partner that uses some of the common things but uses a different compiler. So the warning # are different.
The only way i could think of doing was making a macro that was defined in a file that i would pass in some generic value:
SUPPRESS_WARNING_BEGIN(NEVER_USED)
//code
SUPPRESS_WARNING_END
then the file would have something like:
#if COMPILER_A
NEVER_USED = 245
#endif
#if COMPILER_B
NEVER_USED = 332
#endif
#define SUPPRESS_WARNING_BEGIN(x) /
#if COMPILER_A
//Compiler A suppress warning x
#endif
#if COMPILER_B
//Compiler B suppress warning x
#endif
#define SUPPRESS_WARNING_END /
#if COMPILER_A
// END Compiler A suppress warning
#endif
#if COMPILER_B
// END Compiler A suppress warning
#endif
Don't know if there is an easier way? Also i know ideally we all would just use the same compiler but that is unfortunately not an option. Just trying to find the least complicated way to support something like this and am hoping there is a simpler way then mentioned above.
thanks
There's no portable way to do that. Different compilers do it in different ways (e.g. #pragma warning, #pragma GCC diagnostic, etc.).
The easiest and best thing to do is to write code that does not generate any warnings with at compiler at any warning level.
If your goal is to suppress warnings about unused variables, I recommend using a macro:
#define UNUSED(x) ((void)sizeof(x))
...
void some_function(int x, int y)
{
// No warnings will be generated if x is otherwise unused
UNUSED(x);
....
}
The sizeof operator is evaluated at compile-time, and the cast to void produces no result, so any compiler will optimize the UNUSED statement away into nothing but consider the operand to be used.
GCC also has the unused attribute`:
// No warnings will be generated if x is otherwise unused
int x __attribute__((unused));

Disable single warning error

Is there a way to disable just a single warning line in a cpp file with visual studio?
For example, if I catch an exception and don't handle it, I get error 4101 (unreferenced local variable). Is there a way to ignore this just in that function, but otherwise report it in the compilation unit? At the moment, I put #pragma warning (disable : 4101) at the top of the file, but that obviously just turns it off for the whole unit.
#pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop )
If you only want to suppress a warning in a single line of code (after preprocessing)[1], you can use the suppress warning specifier:
#pragma warning(suppress: 4101)
// here goes your single line of code where the warning occurs
For a single line of code, this works the same as writing the following:
#pragma warning(push)
#pragma warning(disable: 4101)
// here goes your code where the warning occurs
#pragma warning(pop)
[1] Others have noted in comments below that if the following statement is an #include statement that the #pragma warning(suppress: 4101) statement would not effectively suppress the warning for every line in the header file. If one were intending to do that, one would need to utilize the push/disable/pop method instead.
#pragma push/pop are often a solution for this kind of problems, but in this case why don't you just remove the unreferenced variable?
try
{
// ...
}
catch(const your_exception_type &) // type specified but no variable declared
{
// ...
}
Example:
#pragma warning(suppress:0000) // (suppress one error in the next line)
This pragma is valid for C++ starting with Visual Studio 2005.
https://msdn.microsoft.com/en-us/library/2c8f766e(v=vs.80).aspx
The pragma is NOT valid for C# through Visual Studio 2005 through Visual Studio 2015.
Error: "Expected disable or restore".
(I guess they never got around to implementing suppress ...)
https://msdn.microsoft.com/en-us/library/441722ys(v=vs.140).aspx
C# needs a different format. It would look like this (but not work):
#pragma warning suppress 0642 // (suppress one error in the next line)
Instead of suppress, you have to disable and enable:
if (condition)
#pragma warning disable 0642
; // Empty statement HERE provokes Warning: "Possible mistaken empty statement" (CS0642)
#pragma warning restore 0642
else
That is SO ugly, I think it is smarter to just re-style it:
if (condition)
{
// Do nothing (because blah blah blah).
}
else
Use #pragma warning ( push ), then #pragma warning ( disable ), then put your code, then use #pragma warning ( pop ) as described here:
#pragma warning( push )
#pragma warning( disable : WarningCode)
// code with warning
#pragma warning( pop )
as #rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop
this info comes from here
One may also use UNREFERENCED_PARAMETER defined in WinNT.H. The definition is just:
#define UNREFERENCED_PARAMETER(P) (P)
And use it like:
void OnMessage(WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(wParam);
UNREFERENCED_PARAMETER(lParam);
}
Why would you use it, you might argue that you can just omit the variable name itself. Well, there are cases (different project configuration, Debug/Release builds) where the variable might actually be used. In another configuration that variable stands unused (and hence the warning).
Some static code analysis may still give warning for this non-nonsensical statement (wParam;). In that case, you mayuse DBG_UNREFERENCED_PARAMETER which is same as UNREFERENCED_PARAMETER in debug builds, and does P=P in release build.
#define DBG_UNREFERENCED_PARAMETER(P) (P) = (P)
Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.
Although there are some other options, including #pramga warning (once).
This question comes up as one of the top 3 hits for the Google search for "how to suppress -Wunused-result in c++", so I'm adding this answer here since I figured it out and want to help the next person.
In case your warning/error is -Wunused (or one of its sub-errors) or -Wunused -Werror only, the solution is to cast to void:
For -Wunused or one of its sub-errors only1, you can just cast it to void to disable the warning. This should work for any compiler and any IDE for both C and C++.
1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase "All the above -Wunused options combined" and look there for the main -Wunused warning and above it for its sub-warnings. The sub-warnings that -Wunused contains include:
-Wunused-but-set-parameter
-Wunused-but-set-variable
-Wunused-function
-Wunused-label
-Wunused-local-typedefs
-Wunused-parameter
-Wno-unused-result
-Wunused-variable
-Wunused-const-variable
-Wunused-const-variable=n
-Wunused-value
-Wunused = contains all of the above -Wunused options combined
Example of casting to void to suppress this warning:
// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var; // <===== SOLUTION! ======
For C++, this also works on functions which return a variable marked with [[nodiscard]]:
C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)
So, the solution is to cast the function call to void, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]] attribute) to void.
Example:
// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass
{
public:
// fill in class details here
private:
// fill in class details here
};
// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
MyNodiscardClass myNodiscardClass;
return myNodiscardClass;
}
int main(int argc, char *argv[])
{
// THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
// IF YOU HAVE `-Wunused` turned on, since you are
// discarding a "nodiscard" return type by calling this
// function and not using its returned value!
MyFunc();
// This is ok, however, as casing the returned value to
// `void` suppresses this `-Wunused` warning!
(void)MyFunc(); // <===== SOLUTION! ======
}
Lastly, you can also use the C++17 [[maybe_unused]] attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.
If you want to disable unreferenced local variable write in some header
template<class T>
void ignore (const T & ) {}
and use
catch(const Except & excpt) {
ignore(excpt); // No warning
// ...
}
In certain situations you must have a named parameter but you don't use it directly.
For example, I ran into it on VS2010, when 'e' is used only inside a decltype statement, the compiler complains but you must have the named varible e.
All the above non-#pragma suggestions all boil down to just adding a single statement:
bool f(int e)
{
// code not using e
return true;
e; // use without doing anything
}