Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to treat specific warnings as errors in c++ to be cross-platform?

I need to treat some specific warnings as errors to ensure the program runs as it is supposed to. For instance functions with [[nodiscard]] attribute should always return, otherwise the compiler prints an error. In Visual Studio (MSVC), it is easy to do that with:

#pragma warning (error: warning_id)

This works perfectly. But I run this code on a cluster, where I use either GCC, Clang or the Intel compiler, so I would like to implement this to be portable. Something like:

#if defined(_MSC_VER)
    #pragma warning (error: 4834)
#elif defined(__GNUC__)
    // what here?
#elif defined(__clang__)
    // what to put here?
#else
    // another compiler...
#endif

I suppose Intel is similar to MSVC; in Clang, there is an option to treat an error as warning -Wno-error=some_error, which would help me the other way around but there may be too many warnings, which I would rather not treat as errors.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anybody help with this?

>Solution :

For GCC and clang, the #pragma to elevate a specific warning to an error is very similar.

For GCC:

#pragma GCC diagnostic error "-Wunused-result"

For clang:

#pragma clang diagnostic error "-Wunused-result"

The Intel C/C++ compiler does, as you presume, support the MSVC-style #pragma (and it also defines the _MSC_VER macro, so you can use the same #if defined... block).

For "other" compilers, it’s clearly very difficult to say – you would need to check the manual for each compiler you are likely to use. As far as I know, there is no standard (cross-platform) way to do this. Also note that, just because a compiler pre-defines the _MSC_VER macro, does not guarantee that it will also support all MSVC-style #pragma syntax.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading