c++clangllvm-c++-api

Using clang as a library in C++ project


I am trying to use clang as a library, but I am not sure how to link the files in the Makefile.

Trying out the ASTVisitor code from: https://clang.llvm.org/docs/RAVFrontendAction.html

Here is my Makefile for reference:

CC=g++
Includes= /usr/lib/llvm-6.0/include/
Libs= /usr/lib/llvm-6.0/lib/
CLANGLIBS=-lclangTooling -lclangFrontendTool -lclangFrontend -lclangDriver -lclangSerialization -lclangCodeGen -lclangParse -lclangSema -lclangStaticAnalyzerFrontend -lclangStaticAnalyzerCheckers -lclangStaticAnalyzerCore -lclangAnalysis -lclangARCMigrate -lclangRewrite -lclangRewriteFrontend -lclangEdit -lclangAST -lclangLex -lclangBasic -lclang

run:
    LD_PRELOAD=../../llvm-project/build/lib/libclang.so ./clang_parser.out

all: clang_parser.cpp
    $(CC) -I$(Includes) -L$(Libs) clang_parser.cpp -o a.out $(CLANGLIBS)
clean:
    rm clang_parser.out

I have installed clang as a library i.e. done sudo apt-get install libclang-dev

I get the following error:

clang_parser.cpp:13:10: fatal error: clang/Frontend/FrontendActions.h: No such file or directory
#include <clang/Frontend/FrontendActions.h>
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
Makefile:10: recipe for target 'all' failed
make: *** [all] Error 1

Any best practices on using apt installed packages in C/C++ projects are appreciated too.


Solution

  • Installed a number of packages just to make sure:

    sudo apt-get install libclang-dev llvm clang clang-tools
    

    This is the compilation command for reference (it includes all libraries which may be used):

    clang++ `llvm-config --cxxflags --ldflags` clang_parser.cpp $(CLANGLIBS2) `llvm-config --libs --system-libs` -g -o tool
    

    where

    CLANGLIBS2=-lclangTooling -lclangFrontendTool -lclangFrontend -lclangDriver -lclangSerialization -lclangCodeGen -lclangParse -lclangSema -lclangStaticAnalyzerFrontend -lclangStaticAnalyzerCheckers -lclangStaticAnalyzerCore -lclangAnalysis -lclangARCMigrate -lclangRewrite -lclangRewriteFrontend -lclangEdit -lclangAST -lclangASTMatchers -lclangLex -lclangBasic -lclang
    

    Set up all .so, .a files in /usr/lib/llvm-6.0/lib as LD_LIBRARY_PATH by doing:

    export LD_LIBRARY_PATH=/usr/lib/llvm-6.0/lib
    ldconfig