调用Eclipse CDT解析器的结果实现对C++代码的解析
作者:天涯 来源:中国自学编程网 发布日期:1228350297
引入org.eclipse.cdt.core的插件包后.通过如下代码则可获得某个C++源文件的解析结果

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表示一个编译单元.可以是一个项目.一个文件.文件的一个代码块ASTTranslatonUnit 是编译单元的AST表示.里面包含了所有的信息