且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跨平台宏,用于沉默未使用的变量警告

更新时间:2022-12-22 16:30:07

Yup - 您可以对GCC和Clang使用此方法:



#define MON_Internal_UnusedStringify(macro_arg_string_literal)#macro_arg_string_literal

#define MONUnusedParameter(macro_arg_parameter)_Pragma(MON_Internal_UnusedStringify $ b

虽然我们已经定义了(void)对于clang,看起来Clang现在支持stringify和 _Pragma 方法。 _Pragma 为C99。


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?

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.