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?

2
  • 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. Commented Jul 25, 2019 at 14:42
  • The Core Guidelines 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. Commented Feb 28, 2020 at 7:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.