1. 程式人生 > >msvc/gcc:中用#pragma指令關閉特定警告(warning)

msvc/gcc:中用#pragma指令關閉特定警告(warning)

參考資料 顯示 msvc temp cpp get 自己 http https

在使用一些第三方庫或源碼的時候,經常會遇到編譯時產生warnings情況,這些warning不是我們自己的代碼產生的,當然也不好去修改,但每次編譯都顯示一大堆與自己代碼無關的警告也著實看著不爽,更麻煩的是還有可能造成自己代碼中產生的警告被淹沒在多過的無關警告中,而被忽略掉的情況。
所以要想辦法關閉這些第三方代碼和庫產生的警告。
關閉特定的warning可以在編譯時通過命令行參數的方式指定,比如 gcc 是在命令行一般是用-Wno-xxxx這樣的形式禁止特定的warning,這裏xxxx代入特定的警告名。但這種方式相當將所有代碼產生的這個warning顯示都關閉了,不管是第三方庫產生的還是自己的代碼產生的,所以這種用法並不適合。

關閉特定的warning還可以在代碼中通過添加#pragma指令來實現,用#pragma指令可以對指定的區域的代碼關閉指定的warning。

msvc下的用法是這樣的

#ifdef _MSC_VER
// 關閉編譯CImg.h時產生的警告
#pragma  warning( push ) 
#pragma  warning( disable: 4267 4319 )
#endif
#include "CImg.h"
#ifdef _MSC_VER
#pragma  warning(  pop  ) 
#endif

gcc下的用法是這樣的:

#ifdef __GNUC__
// 關閉 using  _Base::_Base; 這行代碼產生的警告
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winherited-variadic-ctor"
#endif
.....
namespace cimg_library {
template<typename T>
class CImgWrapper:public CImg<T> {
public:
    using   _Base =CImg<T>;
    using  _Base::_Base; // 繼承基類構造函數
    ......
}
} /* namespace cimg_library */
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

參考資料:
https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas

msvc/gcc:中用#pragma指令關閉特定警告(warning)