4

Clang-tidy's cppcoreguidelines-pro-type-union-access rule is essentially a complete ban on unions, it flags all access to union members.

My library has an extern "C" interface with a structure which contains an union. I cannot use variants in headers that should be usable from C and not only C++.

Obviously spamming the code with NOLINT everywhere where I'm using union is not a good idea.

Are there any workarounds other than just disabling this check?

timrau
  • 22,578
  • 4
  • 51
  • 64
Calmarius
  • 18,570
  • 18
  • 110
  • 157
  • 2
    If your library knowingly and rightfully uses unions, why do you need the check at all? Disable it for this file. That check isn't great, in my view. There is no shortage of C++ programs interacting with legacy C interfaces (network stack is the first thing which comes to mind), and if all of those are flagged, it is just spam. – SergeyA Jul 25 '19 at 14:42
  • The [Core Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#prosafety-type-safety-profile) say "Type.7: Avoid naked union: Use variant instead." If this is not possible in your case because of C interop, then you can only suppress or disable this check. – Werner Henze Feb 28 '20 at 07:23

1 Answers1

0

This depends on your usage of unions, especially on how scattered over your code the union usage mentioned in your question is. If you use it all over the place there's not much you can do apart from disabling the check.

If it's constrained to several specific places you can use the -line-filter option to filter out files (or even lines) where this is used. The tricky part is that -line-filter filters lines IN.

This filters out all warnings from unions.cpp (assuming it has less than 9999999 lines):

-line-filter=[{"name":"unions.cpp","lines":[[9999999,9999999]]},{"name":".h"},{"name":".cpp"}]

{"name":".h"},{"name":".cpp"} filters in the rest of the files, otherwise you would see no warnings at all.

Alternately if you would like only to filter out some lines from unions.cpp:

-line-filter=[{"name":"unions.cpp","lines":[[1,10],[12,100]]}},{"name":".h"},{"name":".cpp"}]

Line 11 will be skipped in this example.

Obviously this would filter out warnings for all checks from that file (or lines) so you may want to run that check separately.

pablo285
  • 2,460
  • 4
  • 14
  • 38