Search code examples
c++compiler-warningssuppress-warnings

How to ignore compiler warnings for macros defined in third-party headers?


Currently it's possible to tell the compiler to ignore warnings from a given header by considering it a "system header", including the header via -isystem /path/to/dir.

However, this still won't work if the warning stems from a macro defined in such a header. Is there any way to ignore warnings also for macros? I'm mostly interested in GCC and Clang solutions.

Examples below are based on Clang 14.0.0 and GCC 11.1.0 on Ubuntu 20.04:

// include/third_party.h
#pragma once

#define MY_CAST(x) ((int)x)
// main.cpp
#include <third_party.h>

int main() 
{
    int x = MY_CAST(123);
    return x;
}

With GCC:

$ g++ -isystem include -Wold-style-cast main.cpp 
In file included from main.cpp:1:
main.cpp: In function ‘int main()’:
main.cpp:5:21: warning: use of old-style cast to ‘int’ [-Wold-style-cast]
    5 |     int x = MY_CAST(123);
      |                     ^~~

With Clang:

$ clang++ -isystem include -Wold-style-cast main.cpp
$

Example that works with GCC but not with Clang:

// include/third_party2.h
#pragma once

struct Foo
{
    int x;
    int y;
};

#define FOO Foo{.x = 123, .y = 321}
// main.cpp
#include <third_party2.h>

int main() 
{
    Foo f = FOO;
    return f.x;
}

$ g++ -isystem include -pedantic main2.cpp
$
$ clang++ -isystem include -pedantic main2.cpp 
main2.cpp:5:13: warning: designated initializers are a C++20 extension [-Wc++20-designator]
    Foo f = FOO;
            ^
include/third_party2.h:9:17: note: expanded from macro 'FOO'
#define FOO Foo{.x = 123, .y = 321}
                ^
1 warning generated.

Solution

  • The issue seems to be simply a bug in GCC/Clang. In general, warnings are expected to be ignored when coming from system macros, and most of them are ignored. I just happen to have come across very concrete use cases where the warning is not ignored.

    In case someone is interested in the GCC issue, here's the bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103862

    For Clang, I've asked a general question here: https://lists.llvm.org/pipermail/cfe-dev/2021-December/069648.html

    And reported issue here: https://github.com/llvm/llvm-project/issues/52944

    Bonus: for clang-tidy, I have a patch to make sure warnings from macros are ignored: https://reviews.llvm.org/D116378

    Thanks everyone for contributing to this investigation!