user3162587
user3162587

Reputation: 233

How to compile C++ codes with clang/LLVM libraries?

I'm new to Linux and working through some clang tutorials. However, I find it hard to compile even a simple file. So, here is part of the code:

#include <cstdio>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <utility>
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/ParseAST.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"

using namespace clang;
using namespace std;

When I'm trying to compile the simple code (let's say PrintFunctions.cpp) with the following command:

clang++ -o PrintFunctions PrintFunctions.cpp

and I get the error:

fatal error: 'clang/AST/ASTConsumer.h' file not found

Well, I have checked that my LLVM and clang has been well installed, and the file 'clang/AST/ASTConsumer.h' is found under

/usr/lib/llvm-3.4/include/clang/AST

So, there must be something I missed in command. I have no idea of what to do... I have read some tutorials online and most of them used makefile, and they seems to be complicated. So, how to compile it? How to find an easier way to write makefile?

BTW, I'm under Ubuntu 14.04, and clang/LLVM version is 3.4.

Upvotes: 2

Views: 2337

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

Typically, in your makefile, you should have something like:

CXXFLAGS += `${LLVM_DIR}/bin/llvm-config --cxxflags`

and

LDFLAGS += `${LLVM_DIR}/bin/llvm-config --ldflags`
LLVMLIBS = `${LLVM_DIR}/bin/llvm-config --libs`

[edit per comment by Thomas]

You will probably also use:

LLVMLIBS += `${LLVM_DIR}/bin/llvm-config --system-libs`

for things that aren't part of LLVM, but that LLVM relies on.

[end edit]

and then using these:

.cpp.o: 
    ${CXX} ${CXXFLAGS} ${CXX_EXTRA} -c -o $@ $<

myprog: ${OBJECTS}
    ${LD} ${LDFLAGS} -o $@ ${OBJECTS} ${LIBS}

(Where ${OBJECTS} is the list of your object files)

LLVM_DIR should of course be set to point to where your LLVM is installed, e.g. /usr/ or /usr/local - run which clang++ to see where your clang is installed.

Here's my Makefile for my Pascal compiler, using LLVM as the backend.

Upvotes: 6

Related Questions