#warning和#error作为宏

#warning and #error as Macro

本文关键字:#error #warning      更新时间:2023-10-16

是否有办法在编译时使用宏来强制警告和错误?

我现在有这样的东西:

#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 '指令不同,这些pragmas可以使用' _Pragma '嵌入到预处理器宏中。

测试表明这些也可以在clang中工作。

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

根据所讨论的特定宏,另一种选择可能是强制函数调用带有warningerror属性的函数。与pragmas不同的是,如果函数调用已知不可达(例如,因为它出现在if块中,在编译时检测到条件总是为false),则属性没有作用,因此,如果在这种情况下,您希望抑制警告或错误,则它们可能更合适。

相关文章: