Mixed C/C++ Project: C++ rules applied to included C headers

I have a mixed C++/C project. The C sources are always included with surrounding extern "C" { #include "cHeader.h" }.

The problem is I’m getting C++ rules (such as cpp:S5416 "using” should be preferred for type aliasing) applied to C header that I (directly or indirectly) include in C++ files.

Is this a known issue or is there any workaround or preferred way of handling this?

SonarQube server 8.9.0, SonarScanner, sonar.cfamily

Hello @Sidelobe ,

Thank you for reporting this. Does this happen with many rules?
Header files are analyzed in the context of the compilation unit that was built. So if the header is included in a C++ file, it will be analyzed with C++ rules (even though it is surrounded with extern "C"). We understand this is a problem in your case and we’ll keep it in mind to improve that.

For the time being, I can think of two possible workarounds (and I apologize in advance, I know they are not ideal):

  • If this problem does not occur for many files, you can exclude the files from the analysis (using sonar.exclusions for example). You can also exclude some rules for some files (see " Ignore Issues on Multiple Criteria" paragraph in Documentation: Narrowing the Focus)

  • Otherwise, you can do 2 different analysis based on the same build-wrapper output. One analysis would be only for *.c and *.h files, and the other one would be for *.cpp only, excluding *.h files that are related to *.c files

Hello @Amelie

Thanks for your reply – it does not happen with too many rules, from what I can tell.

Other ‘culprits’ I have:

  • cpp:S3642 Scoped enumerations should be used
  • cpp:IdentifierLongerThan31 (this one happens a loooot – since C functions have to include a unique namespace prefix)

I think explicitly adding this to the .properties file improved the situation a little bit:

I was under the impression this was the default anyway.

About the second option you suggest: would this basically mean calling the scanner twice with 2 .properties files? I guess I should use different project keys in this scenario, so the results don’t overwrite each other, right?

Okay, thanks for the information!

Yes, the suffixes you have written down are supposed to be the default ones (you can check what they are in your SonarQube instance: Administration at the top > Languages > Select “C / C++ / Objective-C”).

About the second option:
Yes exactly.
If you have set your options in a “sonar-project.properties” file, you can create two different “*.properties” files and call sonar-scanner with each one of them
eg: sonar-scanner -Dproject.settings=myproject.properties