📅 2010-Jul-27 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ pragma, visual cpp, warnings ⬩ 📚 Archive
It is a good practice to compile code at the highest warning level available from the compiler. When the compiler reports warnings on the code, the code should be fixed so that it compiles with zero warnings. But, sometimes this is not possible, for example, if the source of the warnings are headers included from external libraries. Common C++ libraries like Boost and special libraries like CGAL (Computational Geometry Algorithms Library) are notorious for introducing hundreds of warnings when their header files are included.
In Visual C++, the #pragma warning compiler directive is an effective way to disable these specific warnings. There are many specifiers that can be specified with #pragma warning. Here are a couple that I find most useful:
Warnings that are reported have an identifier and a textual message. The identifier is of the form CXXXX, where XXXX is the warning number. The disable specifier can be used to disable a specific warning, say C1234:
#pragma warning(disable: 1234)
The disabling of warnings should be localized as much as possible. This can be done using the push and pop specifiers around the offending code.
#pragma warning(push)
#pragma warning(disable: 1234)
// Offending code that produces C1234 warning goes here
#pragma warning(pop)
#pragma warning directives can be placed in header files or in source files. When the directive needs to be used across an entire source file or many files, one can get lazy and place it in a header that is included in all these files. This is not a good practice since the warning will be disabled for all the source files that include that header now or in the future.
I prefer placing directives at the source file level, so that their effect is localized to the source file. If one is placing the directive at the source file, it should be put at the top, even above the header files inclusion, to be effective:
// Foo.cpp
#pragma warning(disable: 1234)
#include "Foo.h"
Foo::Foo()/***/ } {