#warning和#error为宏

时间:2014-06-14 22:54:02

标签: c++ c macros

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

我目前有这样的事情:

#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

1 个答案:

答案 0 :(得分:5)

是的,有。引用GCC preprocessor documentation

#pragma GCC warning
#pragma GCC error
     

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

测试显示这些也适用于clang。

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

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