Skip to content

Instantly share code, notes, and snippets.

@eonil
Last active August 29, 2015 14:13
Show Gist options
  • Save eonil/fb3404c93d73179ff9cd to your computer and use it in GitHub Desktop.
Save eonil/fb3404c93d73179ff9cd to your computer and use it in GitHub Desktop.

libclang Note

  • Use C API that is intended to be stable long term API.
  • C++ interfaces are not really an API. So it constantly changes.

Caveats

  • clang_parseTranslationUnit requires passing number of arguments in C array. It does not depends on terminating NULL.
  • Parser uses filename extension to select parsing mode. Pass -std=c11 to force C++ parsing for .h files. Otherwise it will be defaulted to some old-school C.

Minimal Example 1 (3.6svn)

#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS

#include <unistd.h>
#include <iostream>
#include <vector>
#include <string>
#include <memory>

#include <llvm/Support/raw_ostream.h>

#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>

using namespace std;
using namespace clang;

int main(int argc, const char * argv[]) {
	
	FileSystemOptions		fmopts		{};
	FileManager				fm			{fmopts};

	DiagnosticsEngine		dengine		{nullptr, nullptr};

	std::shared_ptr<TargetOptions>	targetopts	=	std::make_shared<TargetOptions>();
	targetopts->Triple	=	llvm::sys::getDefaultTargetTriple();
	
	TargetInfo*				target		=	TargetInfo::CreateTargetInfo(dengine, targetopts);

	SourceManager			SM			{dengine, fm};
	LangOptions				langopts	{};
	HeaderSearch			headers		{nullptr, SM, dengine, langopts, target};

	
	llvm::raw_fd_ostream	ost(STDIN_FILENO, false, true);
	
	DiagnosticOptions		dops	{};
	TextDiagnosticPrinter	tdp		{ost, &dops};
	LangOptions				lang	{};
	CompilerInstance		comp	{};
	
	Preprocessor			prep	{nullptr, dengine, langopts, SM, headers, comp};

	// insert code here...
	std::cout << "Hello, World!\n";
    return 0;
}

Anyway, this still crashes...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment