#warning和#error为宏

有没有办法让宏在编译时强制警告和错误?

我目前有这样的事情:

#if defined( __clang__ ) # define PRAGMA( x ) _Pragma( #x ) #elif defined( __GNUC__ ) # define PRAGMA( x ) _Pragma( #x ) #elif defined( _MSC_VER ) # define PRAGMA( x ) __pragma( x ) #endif #define STRINGISIZE( str ) #str #define STR( str ) STRINGISIZE( str ) #define LINE STR( __LINE__ ) #define FILE __FILE__ #define FILE_LINE __FILE__ "(" LINE ")" #define INFO( info , msg ) \ PRAGMA( message( FILE_LINE ": " #info ": " msg ) ) #define MESSAGE( m ) INFO( msg , m ) #define WARNING( w ) INFO( warning , w ) #define ERROR( e ) INFO( error , e ) #define TODO( t ) INFO( TODO , t ) int main() { MESSAGE( "MSG" ) TODO( "TODO" ) WARNING( "WARN" ) ERROR( "ERROR" ) } 

Visual Studio 2013会将这些宏视为警告/错误,此示例将无法编译。 是否有GCC和Clang的等价物?


 #if defined( _MSC_VER ) #define INFO( info , msg ) \ PRAGMA( message( FILE_LINE ": " #info ": " msg ) ) #define MESSAGE( m ) INFO( info , m ) #define WARNING( w ) INFO( warning , w ) #define ERROR( e ) INFO( error , e ) #define TODO( t ) INFO( todo t ) #elif defined( __GNUC__ ) || defined( __clang__ ) #define INFO( info , msg ) \ PRAGMA( #info " : " #msg ) ) #define MESSAGE( m ) INFO( info , m ) #define WARNING( w ) INFO( GCC warning , w ) #define ERROR( e ) INFO( GCC error , e ) #define TODO( t ) INFO( , "todo" t ) #endif 

就在这里。 引用GCC预处理器文档 :

 #pragma GCC warning #pragma GCC error 

#pragma GCC warning "message"使预处理器发出带有文本“ message ”的警告诊断。 pragma中包含的消息必须是单个字符串文字。 同样, #pragma GCC error "message"发出错误消息。 与’ #warning ‘和’ #error ‘指令不同,这些编译指示可以使用’ _Pragma ‘嵌入到预处理器宏中。

测试显示这些也与clang一起工作。

请注意,您不需要嵌入文件和行信息。 该指令将作为常规诊断输出,所有诊断都包含文件和行信息。

根据所讨论的特定宏,另一个选项可能是强制对标有warningerror属性的函数进行函数调用。 与pragma不同,如果已知函数调用无法访问,则属性不起作用(例如,因为它出现在if块中,在编译时检测到条件总是为false),所以如果在这种情况下你想要要被抑制的警告或错误,它们可能更合适。