0

I'm trying to use the libclang API to programmatically analyze a C++ project. I have clang compiling fine, and my tool is properly parsing the generated AST, but I can't figure out how to turn on/off specific warnings.

here is the relevant code snippet, I would like to enable/disable the "unused variable" warning:

        clang::DiagnosticOptions mDiagnosticOptions;
        mDiagnosticOptions.ShowOptionNames      = 1; // prints warning, ie [-Wextra-tokens]
        mDiagnosticOptions.Warnings.push_back("unused-variable"); // <----- DOESN'T WORK

        // use mDiagnosticOptions further down for compile steps etc.
        .
        .
        .
Scott McPeak
  • 8,803
  • 2
  • 40
  • 79

2 Answers2

1

Your code snippet is not part of the libclang API (clang-c/Index.h). If you're using libclang, then you obtain a translation unit by a call to

CXTranslationUnit clang_parseTranslationUnit(
        CXIndex CIdx,
        const char *source_filename,
        const char * const *command_line_args,
        int num_command_line_args,
        struct CXUnsavedFile *unsaved_files,
        unsigned num_unsaved_files,
        unsigned options);

You can disable warnings via the command_line_args argument, e.g.,

const char* const command_line_args[] = { "-Wall", "-Wno-unused-variable" };
  • The OP's question relates to [libtooling](https://clang.llvm.org/docs/LibTooling.html), the C++ API, rather than [libclang](https://clang.llvm.org/doxygen/group__CINDEX.html), the C API. But this answer is useful for the latter. – Scott McPeak Jul 14 '23 at 18:54
0

I think the issue here is in the "use mDiagnosticOptions further down for compile steps etc." part of the code. In particular, if you are using the LoadFromCommandLine method of ASTUnit, you have to pass a DiagnosticsEngine, which contains a DiagnosticOptions, so naively it seems like you should configure that DiagnosticOptions to choose what warnings to enable.

However, LoadFromCommandLine parses its command line, and in doing so will overwrite some of the information in DiagnosticOptions, such as its Warnings and IgnoreAllWarnings fields. (But it does not overwrite ShowOptionNames; the details of what survives are not documented, and presumably arise from how the parser is written.)

Therefore, you have to enable and disable warnings using the command line syntax:

commandLine.push_back("-Wunused-variable");     // enable one warning
commandLine.push_back("-Wno-unused-variable");  // disable one warning
commandLine.push_back("-w");                    // disable all warnings

before passing commandLine to LoadFromCommandLine.

Scott McPeak
  • 8,803
  • 2
  • 40
  • 79