#warning和#error作为宏
#warning and #error as Macro
是否有办法在编译时使用宏来强制警告和错误?
我现在有这样的东西:
#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中工作。
注意,您不需要嵌入文件和行信息。该指令将作为常规诊断输出,并且所有诊断都包含已经存在的文件和行信息。
根据所讨论的特定宏,另一种选择可能是强制函数调用带有warning
或error
属性的函数。与pragmas不同的是,如果函数调用已知不可达(例如,因为它出现在if
块中,在编译时检测到条件总是为false),则属性没有作用,因此,如果在这种情况下,您希望抑制警告或错误,则它们可能更合适。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- C++错误:"error: int aaa::bbb is protected within this context"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- C++ "error: invalid use of void expression"
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 如何修复"error: ‘_1’ was not declared in this scope"?
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 从不同目录执行时"symbol lookup error:",否则从构建目录执行时按预期工作
- 对象声明中的模板"error: expected expression"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- OpenCV 3.4.1 error readNetFromTensorflow 无法在 cv::d nn::ReadProtoFromBinaryFile 中打开 .pb
- 已解决 - C++ 的崇高文本中的"fatal error: opencv: no such file or directory"
- cuda-gdb 给出错误"warning: Cuda API error detected: cudaLaunchKernel returned (0x7)"
- 制作 - 特定文件的"Treat warning as error"
- #warning和#error作为宏