How to suppress GCC warnings from library headers?

2019-01-02 20:07发布

I have a project that uses log4cxx, boost, etc. libraries whose headers generate lots of (repetitive) warnings. Is there a way to suppress warnings from library includes (i.e. #include <some-header.h>) or includes from certain paths? I'd like to use -Wall and/or -Wextra as usual on project code without relevant info being obscured. I currently use grep on make output but I'd like something better.

8条回答
旧时光的记忆
2楼-- · 2019-01-02 20:37

There must be reasons for those warnings. These will either be caused by errors in your code that uses the library, or by errors in the library code itself. In the first case, fix your code. In the second case, either stop using the library or if it is FOSS code, fix it.

查看更多
宁负流年不负卿
3楼-- · 2019-01-02 20:41

You can try using precompiled headers. Warnings won't go away but at least the won't show up in your main compilation.

查看更多
浅入江南
4楼-- · 2019-01-02 20:43

For those using CMake, you can modify your include_directories directives to include the symbol SYSTEM which suppresses warnings against such headers.

include_directories(SYSTEM "${LIB_DIR}/Include")
                    ^^^^^^
查看更多
大哥的爱人
5楼-- · 2019-01-02 20:44

You can use pragmas. For example:

// save diagnostic state
#pragma GCC diagnostic push 

// turn off the specific warning. Can also use "-Wall"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>

// turn the warnings back on
#pragma GCC diagnostic pop
查看更多
浅入江南
6楼-- · 2019-01-02 20:46

If you need to explicitly override a system header then you're restricted to pragmas. You can verify which includes you're using via make depend output.

Also see diagnostic push-pop for gcc >= 4.6

查看更多
ら面具成の殇う
7楼-- · 2019-01-02 20:48

#pragma are instructions to the compiler. you can set something before the #include and disable it after.

You can also do it at the command line.

Another GCC page specifically on disabling warnings.

I would go for the option of using #pragma's within the source code, and then providing a sound reason (as a comment) of why you are disabling the warnings. This would mean reasoning about the headers files.

GCC approaches this by classifying the warning types. You can classify them to be warnings or to be ignored. The previously linked articles will show you which warnings are may be disabled.

Note: you can also massage the source code to prevent certain warnings by using attributes; however, this bind you quite closely to GCC.

Note2: GCC also uses the pop/push interface as used in microsoft's compiler -- Microsoft disables warnings through this interface. I suggest you investigate this further , as I do not know if it is even possible.

查看更多
登录 后发表回答