我试图在从宏扩展的代码中禁用g ++警告。根据我的理解,_Pragma
应该遵循宏用法,这不应该在用Wparentheses
编译时触发g++
:
#include <stdio.h>
#define TEST(expr) \
int a = 1; \
_Pragma( "GCC diagnostic push" ) \
_Pragma( "GCC diagnostic ignored \"-Wparentheses\"" ) \
if (a <= expr) { \
printf("filler\n"); \
} \
_Pragma( "GCC diagnostic pop" )
int main(){
int b = 2, c = 3;
TEST(b == c);
}
当我用g++
编译它时,我得到Wparentheses
警告,我试图禁用它。
xarn@DESKTOP-B2A3CNC:/mnt/c/ubuntu$ g++ -Wall -Wextra test3.c
test3.c: In function ‘int main()’:
test3.c:8:11: warning: suggest parentheses around comparison in operand of ‘==’ [-Wparentheses]
if (a <= expr) { \
^
test3.c:15:5: note: in expansion of macro ‘TEST’
TEST(b == c);
^
但是,当使用gcc
时,它按预期工作:
xarn@DESKTOP-B2A3CNC:/mnt/c/ubuntu$ gcc -Wall -Wextra test3.c
test3.c: In function ‘main’:
test3.c:16:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
我使用的是g++
版本4.8.5。
通常,您仅使用警告抑制来处理来自第三方代码的不可避免的警告,因此它们不会使编译日志混乱。在你的情况下,它会更好
1)使用常规函数,因为宏是邪恶的
2)通过在可能破坏的表达式周围添加圆括号来处理警告
if (a <= (expr)) {
在使用gcc前端的g ++处理_Pragma
s时存在长期存在的缺陷。唯一的解决方案是要么转到足够现代的g ++版本(IIRC 6+),要么禁用整个TU的警告。