C预处理器如何将函数宏视为字符串

C pre-processor how to treat function macro as string

本文关键字:字符串 函数 预处理 处理器      更新时间:2023-10-16

我使用mingw在OSX for Windows上编译c++代码。c++代码是自动生成的,包括MS Visual studio特有的代码:

class __declspec(novtable) SomeClass

当我编译时,我得到很多警告:

warning: ‘novtable’ attribute directive ignored [-Wattributes]

我想抑制这些警告。Mingw不支持-Wno-microsoft选项,所以我想我可能能够将__declspec(notable)视为指向空字符串的标识符,并让预处理器删除它。

#define __declspec(novtable) 

然而,这被视为__declspec()宏的重新定义,这不是期望的行为。

是否有办法让预处理器将__declspec(novtable)视为标识符,或者以其他方式抑制此警告?(不能修改违规的自动生成代码)。

假设编译器已经生效了这个定义

#define __declspec(x) __attribute__((x))

还可以识别一些(不是全部)microsoft特有的属性,如dllexportdllimport。以下内容只有在上述假设成立的情况下才有意义。

可以使用

 #undef __declspec // to suppress a meessage about macro redefinition
 #define __declspec(x) // nothing

(可能是适当的#ifdef,以免破坏与MSVC的兼容性)。

这将扼杀整个__declspec特性,而不仅仅是__declspec(novtable)。如果这不是你需要的,请继续阅读。

如果你只需要杀死__declspec(novtable)并保持所有其他属性不变,试试这个

#define novtable // nothing

__attribute__指令可能包含一个可能为空的属性列表,因此__declspec(novtable)可能会转换为__attribute__(()),这是完全可以的。这也将杀死所有其他出现的标识符novtable。如果它确实发生在任何其他上下文中,这种情况不太可能发生,但可能发生,则此选项对您不起作用。

另一种可能是接管整个功能。

#undef __declspec
#define __declspec(x) my_attribute_ # x
#define my_attribute_dllexport __attribute__((dllexport)) // or whatever you need
#define my_attribute_dllimport __attribute__((dllimport)) // or whatever you need
// ... same for all attributes you do need
#define my_attribute_novtable // nothing
// ... same for all attributes you don't need

用宏定义你的__declspec(novtable):

 #define DECL_SPEC __declspec(novtable)  

之后你可以这样使用:

 class DECL_SPEC SomeClass 

并在需要时将DECL_SPEC重新定义为空:

 #ifdef __MINGW32__
 #define DECL_SPEC
 #else
 #define DECL_SPEC __declspec(novtable)
 #endif