参考:https://blog.csdn.net/u014520586/article/details/125261494
maven依赖
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>org.eclipse.core.resources</artifactId>
<version>3.7.100</version>
</dependency>
<dependency>
<groupId>com.github.mhoffrog.attached</groupId>
<artifactId>org.eclipse.cdt.core</artifactId>
<version>5.11.0</version>
</dependency>
代码:
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);
}
/**
得到预处理语句
*
* #include <queue>
这⼀类
* #define maxnum 120
*/
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));
}
}
}
/**
* 创建解析单元
*
* @param source
* @return
* @throws Exception
*/
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());
}
/**
* 获得⽂件中的内容
*
* @param file
* @return
* @throws IOException
*/
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();
}
}