2017-03-28 132 views
0

我試圖禁用從宏展開的代碼中的g ++警告。按照我的理解,_Pragma應遵循宏的用法,並正在與g++編譯時,這不應引發WparenthesesG ++忽略忽略_Pragma診斷

#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警告,而我試圖禁用。

[email protected]NC:/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時:

[email protected]:/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。

+0

gcc 4.8.5不會用'gcc -Wall -Wextra test3.c'編譯發佈的源代碼。它會因'致命錯誤:iostream:沒有這樣的文件或目錄'而失敗,因爲'iostream'不是C頭文件。請發佈真實的代碼。 –

+0

@MikeKinghan抱歉,複製粘貼從.cpp文件引發的問題。現在它使用'printf' – Xarn

回答

0

有長g ++處理_Pragma時出現的缺陷,在使用gcc前端時不存在。唯一的解決方案是轉向g ++(IIRC 6+)的足夠現代版本,或者禁用整個TU的警告。

0

您通常使用警告抑制只有應對不可避免的警告來自第三方代碼來使他們不會弄亂編譯日誌。在你的情況下,它會更好地

1)使用常規的功能,因爲宏是邪惡

2)處理警告加圓括號周圍可能存在問題的表達

if (a <= (expr)) { 
+0

有問題的代碼是一個簡單的例子。在真實代碼中,'a'是一個特殊類型的實例,它使用重載的<='運算符來執行魔術。 – Xarn

+1

作爲[運算符重載指南](http://stackoverflow.com/questions/4421706/operator-overloading/4421708#4421708)建議讓重載操作符執行魔術(我猜你的情況<=將返回除bool以外的東西,右?)通常不是一個好主意,通常表明一個邏輯缺陷。將它們混合成宏更加糟糕。 – dodo951

+0

我相當肯定[Catch](https://github.com/philsquared/Catch)和朋友不同意。 – Xarn