maven依赖
org.eclipse.core org.eclipse.core.resources 3.7.100 com.github.mhoffrog.attached org.eclipse.cdt.core 5.11.0
代码:
public class CDTTest {
public static void main(String[] args) throws Exception {
IASTTranslationUnit u = getTranslationUnit(new File("E:\xxx.c"));
//输出的是⽂件的所有内容
// System.out.println("simpleDeclaration.getRawSignature():" + u.getRawSignature());
IASTComment[] com = u.getComments();
for (IASTComment iastComment : com) {
System.out.println("IASTComment:" + iastComment);
}
IASTPreprocessorStatement[] ps = u.getAllPreprocessorStatements();
for (IASTPreprocessorStatement iastPreprocessorStatement : ps) {
System.out.println(iastPreprocessorStatement.getRawSignature());
}
//得到⽂件中定义的声明
IASTDeclaration[] decs = u.getDeclarations();
for (IASTDeclaration child : decs) {
// ⽅法声明
if (child instanceof IASTFunctionDefinition) {
// // 获得函数说明符
// 例
// void
System.out.println(((IASTFunctionDefinition) child).getDeclSpecifier().getRawSignature());
// 获得函数的函数声明符
// 例 函数名
System.out.println(((IASTFunctionDefinition) child).getDeclarator().getRawSignature());
// 获得函数体的内容
System.out.println(((IASTFunctionDefinition) child).getBody().getRawSignature());
// 输出函数的全部内容
System.out.println(child.getRawSignature());
// 与函数的起始位置有关
IASTFileLocation FileLocation = child.getFileLocation();
int startLine = FileLocation.getStartingLineNumber();
int endLine = FileLocation.getEndingLineNumber();
System.out.println("length:" + (endLine - startLine));
}
}
}
static IASTTranslationUnit getTranslationUnit(File source) throws Exception {
FileContent reader = FileContent.create(source.getAbsolutePath(), getContentFile(source).toCharArray());
//C++ 用 GPPLanguage 解析
//C 用 GCCLanguage 解析
return GPPLanguage.getDefault()
.getASTTranslationUnit(reader, new ScannerInfo(), IncludeFileContentProvider.getSavedFilesProvider(), null,
ILanguage.OPTION_IS_SOURCE_UNIT, new DefaultLogService());
// return GCCLanguage.getDefault().getASTTranslationUnit(
// reader,
// new ScannerInfo(),
// IncludeFileContentProvider.getSavedFilesProvider(),
// null,
// ILanguage.OPTION_IS_SOURCE_UNIT,
// new DefaultLogService());
}
static String getContentFile(File file) throws IOException {
StringBuilder content = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
while ((line = br.readLine()) != null) {
content.append(line).append('n');
}
}
return content.toString();
}
}



