Qant123
Qant123

Reputation: 153

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?

Upvotes: 4

Views: 1099

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51835

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.

Upvotes: 6

Related Questions