Xcode 下Libtooling的学习(一)

1.安装clang和llvm

mkdir llvm-clang
cd llvm-clang
git clone https://github.com/llvm/llvm-project.git

使用ninja来编译llvm,并且生成clang,在本例libtooling这个例子中,在clang下面添加一个新的工具。

cd ~/clang-llvm
mkdir build && cd build
cmake -G Ninja ../llvm -DLLVM_ENABLE_PROJECTS="clang" -DLLVM_BUILD_TESTS=ON  # Enable tests; default is off.
ninja
ninja check       # Test LLVM only.
ninja clang-test  # Test Clang only.
ninja install

 

2.创建一个ClangTool

在clang/tools下的CMakeLists.txt加入单句语句,

add_clang_subdirectory(loop-convert)

之后再文档中tools目录下增加官方demo的文件夹,并且创建CMakeList.txt和Loop-Convert.cpp文件。

CMakeLists.txt

set(LLVM_LINK_COMPONENTS support)

add_clang_executable(loop-convert
  LoopConvert.cpp
  )
target_link_libraries(loop-convert
  PRIVATE
  clangTooling
  clangBasic
  clangASTMatchers
  )
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("gouge_-tool options");

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...\n");

int main(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
  ClangTool Tool(OptionsParser.getCompilations(),
                 OptionsParser.getSourcePathList());
  return Tool.run(newFrontendActionFactory().get());
}

在cmake文件中,主要包含了生成可执行文件的source code和以及需要用到的链接库。

cd /path/to/llvm/build
cmake -DLLVM_ENABLE_PROJECTS=clang -G Ninja ../llvm
./bin/loop-convert --help

以上就添加了一个default的libTooling的工具。

REF:

https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html

https://clang.llvm.org/docs/LibTooling.html

https://clang.llvm.org/docs/RAVFrontendAction.html

你可能感兴趣的:(clang,LLVM)