Friday 1 July 2016

Building the Clang AST visitor example on Centos 7

I was struggling to get the AST visitor example (http://clang.llvm.org/docs/RAVFrontendAction.html) to work on Centos 7. These steps allow you to build with yum installed CMake and CLang. I wanted to give it a go to see how easy it would be to create a decent source browser or a tool that can produce Plant UML from existing C++ code. I've refactored the sample to output more information and modified the CMakeLists.txt to work. For each class it will output all the parent contexts (ie namespaces / classes) and all the functions.

Package dependencies


Yum install the following packages:

cmake
clang
clang-devel
libffi
libffi-devel
llvm-devel
llvm-static

I understand Clang shares headers / libs with GNU g++ so I have assumed you already have g++ installed.

CMakeLists.txt


To allow the yum installed CMake to work I had to tweak the tutorial CMakeLists.txt to look like below:

set(CMAKE_CXX_COMPILER "/usr/bin/clang++")
set(CMAKE_C_COMPILER "/usr/bin/clang")
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} /usr/lib64/llvm)

add_definitions(-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS)
project (Tutorial)
add_executable(Tutorial tutorial.cxx)
target_link_libraries(Tutorial /usr/lib64/llvm/libclang.so /usr/lib64/llvm/libLLVM-3.4.so /usr/lib64/llvm/liblldb.so /usr/lib64/llvm/libclangTooling.a)

Build and run

Simply do a "cmake ." followed by "make". This will build an executable called "Tutorial".
You can then just run Tutorial against tutorial.cxx.

compile_commands.json

My example invokes runToolOnCodeWithArgs(). To get the correct arguments you can enable verbose makefile:

cmake -DCMAKE_VERBOSE_MAKEFILE=ON .

This will cause a compile_commands.json to be output. This lists all the arguments you need to pass to Clang for the compilation unit to compile correctly.

Links:




No comments:

Post a Comment