gpt4 book ai didi

c++ - #warning 和 #error 作为宏

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:33 27 4
gpt4 key购买 nike

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

我目前有这样的东西:

#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 preprocessor documentation :

#pragma GCC warning
#pragma GCC error

#pragma GCC warning "message" causes the preprocessor to issue a warning diagnostic with the text ‘message’. The message contained in the pragma must be a single string literal. Similarly, #pragma GCC error "message" issues an error message. Unlike the ‘#warning’ and ‘#error’ directives, these pragmas can be embedded in preprocessor macros using ‘_Pragma’.

测试表明这些也适用于 clang。

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

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

关于c++ - #warning 和 #error 作为宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225006/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com