9

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?

Jean-Denis Muys
  • 6,772
  • 7
  • 45
  • 71

3 Answers3

11
(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.

Christian Stieber
  • 9,954
  • 24
  • 23
  • 1
    Yep except the parameter is used under some set of compile-time conditional compile directive. Additionally, the current case I am facing is not about a parameter but about a local variable. Finally, I try to be minimally intrusive, ie not change the original source code if not necessary, to minimize the time it get accepted at the other end (it still needs to compile and work under Windows). – Jean-Denis Muys Aug 31 '12 at 09:47
5

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.

justin
  • 104,054
  • 14
  • 179
  • 226
1

#define and #pragma both are preprocessor directives. You cannot define one macro to expand as preprocessor directive. Following would be incorrect:

#define MY_MACRO   #if _WIN32 

MY_MACRO cannot expand to #if _WIN32 for the compiler.

Your best bet is to define your own macro:

#define UNUSED(_var) _var
Ajay
  • 18,086
  • 12
  • 59
  • 105