Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cross platform macro for silencing unused variables warning

In porting a large piece of C++ code from Visual Studio (2008) to Xcode (4.4+), I encounter lines such as:

UNUSED_ALWAYS(someVar);

the UNUSED_ALWAYS(x) (through UNUSED(x)) macro expands to x which seems to silence Visual C++ just fine. It's not enough for Clang however.

With Clang, I usually use the #pragma unused x directive.

The UNUSED_ALWAYS and UNUSED macros are defined in an artificial windows.h header which I control that contains a number of utilities to help Xcode compile Windows stuff.

Is there a way to define UNUSED(x) to expand to #pragma unused x? I tried this, which Clang fails to accept:

#define UNUSED(x) #pragma unused(x)

I also tried:

#define UNUSED(x) (void)(x)

Which seems to work. Did I miss anything?

like image 371
Jean-Denis Muys Avatar asked Aug 30 '12 13:08

Jean-Denis Muys


People also ask

How do I get rid of the unused variable warning?

Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.

How to ignore c++ warning?

To disable a set of warnings for a given piece of code, you have to start with a “push” pre-processor instruction, then with a disabling instruction for each of the warning you want to suppress, and finish with a “pop” pre-processor instruction.

What does unused variable mean in C?

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.


2 Answers

(void)x;

is fine; has always worked for me. You can't usually expand a macro to a #pragma, although there is usually a slightly different pragma syntax that can be generated from a macro (_Pragma on gcc and clang, __pragma on VisualC++).

Still, I don't actually need the (void)x anymore in C++, since you can simply not give a name to a function parameter to indicate that you don't use it:

int Example(int, int b, int)
{
   ... /* only uses b */
}

works perfectly fine.

like image 175
Christian Stieber Avatar answered Sep 27 '22 21:09

Christian Stieber


Yup - you can use this approach for GCC and Clang:

#define MON_Internal_UnusedStringify(macro_arg_string_literal) #macro_arg_string_literal

#define MONUnusedParameter(macro_arg_parameter) _Pragma(MON_Internal_UnusedStringify(unused(macro_arg_parameter)))

although mine did have the (void) approach defined for clang, it appears that Clang now supports the stringify and _Pragma approach above. _Pragma is C99.

like image 45
justin Avatar answered Sep 27 '22 19:09

justin