Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I 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 the [[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.

What should I do?

like image 594
Qant123 Avatar asked Oct 23 '25 00:10

Qant123


1 Answers

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 isn't any standard (cross-platform) way to do this. Also note that, just because a compiler predefines the _MSC_VER macro, it does not guarantee that it will also support all MSVC-style #pragma syntax.

like image 67
Adrian Mole Avatar answered Oct 24 '25 13:10

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!