Skip to content

Instantly share code, notes, and snippets.

@ChillMagic
Last active December 9, 2020 12:45
Show Gist options
  • Select an option

  • Save ChillMagic/9a4321cad4c3ffbb322ea81cbec419a8 to your computer and use it in GitHub Desktop.

Select an option

Save ChillMagic/9a4321cad4c3ffbb322ea81cbec419a8 to your computer and use it in GitHub Desktop.
Clang Demo
#include <clang/AST/Expr.h>
#include <clang/Tooling/Tooling.h>
#include <string>
#include <vector>
class ClangIndexer : public clang::ASTFrontendAction {
protected:
virtual std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &ci, llvm::StringRef input_file);
};
class IndexerASTConsumer : public clang::ASTConsumer {
protected:
void HandleTranslationUnit(clang::ASTContext &astcontext) final {
astcontext.getTranslationUnitDecl()->dump();
}
};
std::unique_ptr<clang::ASTConsumer>
ClangIndexer::CreateASTConsumer(clang::CompilerInstance &ci,
llvm::StringRef input_file) {
return std::unique_ptr<clang::ASTConsumer>(new IndexerASTConsumer());
}
auto main() -> int {
llvm::IntrusiveRefCntPtr<clang::FileManager> file_manager(
new clang::FileManager(clang::FileSystemOptions()));
clang::tooling::ToolInvocation invoker(std::vector<std::string>{"clang", "-c", "/home/liangyinan/Code/test/misra/a.c"}, new ClangIndexer(),
file_manager.get());
// invoker.setDiagnosticConsumer(new clang::IgnoringDiagConsumer);
invoker.run();
}
cmake_minimum_required(VERSION 3.5)
project(clangtest)
# Search LLVM
find_package(LLVM REQUIRED CONFIG
HINTS "${LLVM_INSTALL_PREFIX}/lib/cmake/llvm")
find_package(Clang REQUIRED CONFIG
HINTS "${LLVM_INSTALL_PREFIX}/lib/cmake/clang")
include_directories(${LLVM_INCLUDE_DIRS})
add_definitions(${LLVM_DEFINITIONS})
llvm_map_components_to_libnames(LLVM_LIBS Core Support Object)
message(${LLVM_LIBS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fno-rtti")
set(CMAKE_CXX_STANDARD 11)
add_executable(clangtest main.cpp)
target_link_libraries(clangtest ${LLVM_LIBS})
target_link_libraries(clangtest ${LLVM_LIBS} clang clangFrontend clangTooling clangAST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment