'Can clang be told not to analyze certain files?

I'm trying to use clang to profile a project I'm working on. The project includes a rather large static library that is included in Xcode as a dependency.

I would really like clang to not analyze the dependencies' files, as it seems to make clang fail. Is this possible? I've been reading the clang documentation, and I haven't found it.



Solution 1:[1]

As a last resort, there is a brute force option.

Add this to the beginning of a file:

// Omit from static analysis.
#ifndef __clang_analyzer__

Add this to the end:

#endif // not __clang_analyzer__

and clang --analyze won't see the contents of the file.

reference: Controlling Static Analyzer Diagnostics

Solution 2:[2]

Finally, in 2018 the option was implemented.

Use --exclude <path> [1] [2] option

--exclude

Do not run static analyzer against files found in this directory (You can specify this option multiple times). Could be useful when project contains 3rd party libraries.

Solution 3:[3]

I don't use XCode, but using scan-build in linux the following works for me. I my case, I want to run the static analysis on all first party, non-generated code. However, I want to avoid running it on third_party code and generated code.

On the command line, clang-analyzer is hooked into the build when scan-build sets CC and CXX environment variables to ccc-analyzer and c++-analyzer locations. I wrote two simple scripts called ccc-analyzer.py and c++-analyzer.py and hooked them in to the compile in place of the default. In these wrapper scripts, I simply looked at the path of the file being compiled and then run either the raw compiler directly (if I wish to avoid static analysis) or the c*-analyzer (if I wish for static analysis to occur). My script is in python and tied to my specific build system, but as an example that needs modification:

import subprocess
import sys

def main(argv):
  is_third_party_code = False
  for i in range(len(argv)):
    arg = argv[i]
    if arg == '-c':
      file_to_compile = argv[i + 1]
      if '/third_party/' in file_to_compile or \
            file_to_compile.startswith('gen/'):
        is_third_party_code = True
      break
  if is_third_party_code:
    argv[0] = '/samegoal/bin/clang++'
  else:
    argv[0] = '/samegoal/scan-build/c++-analyzer'
  return subprocess.call(argv)

if __name__ == '__main__':
  sys.exit(main(sys.argv))

Solution 4:[4]

For Xcode users, you can exclude individual files from static analyzer by adding the following flags in the Target -> Build Phases -> Compile Sources section: -Xanalyzer -analyzer-disable-all-checks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FluxLemur
Solution 2 The Godfather
Solution 3
Solution 4 Marco