How to selectively ignore a GCC warning

You may sometimes want to ignore or disable a specific type of warning that is generated when compiling your C or C++ code. The diagnostic pragmas of GCC and G++ compilers can be used to achieve this.

  • For example, to ignore the warning of type -Wenum-compare for an entire C++ source file, add this to your code at the top:
#pragma GCC diagnostic ignored "-Wenum-compare"
/**
 * Code that generates this warning
 */
  • If you want the warning to be ignored only for a certain section of the code, surround it with push and pop directives:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wenum-compare"
/**
 * Code that generates this warning
 */
#pragma GCC diagnostic pop

Note: As of GCC 5.1, few of the warnings in G++ (that is, only for C++ code) will not be ignored even when this pragma is used! More details here and here.

Tried with: GCC 4.8 and Ubuntu 12.04 LTS

One thought on “How to selectively ignore a GCC warning”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s