---
title: "如何调用Eclipse CDT解析器的结果实现对C++代码的解析"
author: "tullyliu"
date: "2008-12-03T16:06:33Z"
tags: ["C", "C#", "C++", "Eclipse"]
categories: ["企业架构"]
slug: "eclipse-cdt-c"
draft: false
lastmod: "2008-12-03T17:25:36Z"
id: 285836
url: "https://tullyliu.iteye.com/blog/285836"
---

引入org.eclipse.cdt.core的插件包后.通过如下代码则可获得某个C++源文件的解析结果


```java

public static IASTTranslationUnit getAST( IFile file)  {
		ITranslationUnit tu = CoreModelUtil.findTranslationUnit(file);
		ICProject project= tu.getCProject();
		IASTTranslationUnit ast=null;
		try {
			IIndex index = CCorePlugin.getIndexManager().getIndex(project,
               IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_DEPENDENT);

			index.acquireReadLock();
			try {
				
				ast=tu.getAST(index, 0);
				
			} finally {
				index.releaseReadLock();
			}
		
		} catch (InterruptedException e) {
			//log(e);
		} catch (CoreException e) {
			//log(e);
		}
		return ast;
	}

```


再对IASTTranslatonUnit ast调用 getDeclarations()方法即可获得所有的声明信息
CCorePlugin和CoreModelUtil是CDT Core提供的最重要的入口.
TranslatonUnit表示一个编译单元.可以是一个项目.一个文件.文件的一个代码块
IASTTranslatonUnit 是编译单元的AST表示.里面包含了所有的信息