环境:win7 64位+llvm11+mingw+python3.7+libclang11
基于libclang写了一个提取C语言宏定义的工具
C语言测试代码:
#ifndef DEFAULT_PORT #define DEFAULT_PORT "80" /* Default TCP port for HTTP */ #endif #ifndef MAX_CONTENT_LENGTH #define MAX_CONTENT_LENGTH 250000000 /* Max length of HTTP request content */ #endif #ifndef MAX_CPU #define MAX_CPU 30 /* Max CPU cycles in seconds */ #endif #define MULTIPLY(x, y) x * y #define foo(x) { bar(x); baz(x); } #define PR(...) printf(__VA_ARGS_) #define MacroLog(...)\ {\ FILE* file;\ fopen_s(&file,"./a.txt","a");\ if (file != nullptr)\ {\ fprintf(file, "%s: Line %d:\t", __FILE__, __LINE__);\ fprintf(file, __VA_ARGS__);\ fprintf(file, "\n");\ }\ fclose(file);\ }
python代码
from clang.cindex import Config #配置 from clang.cindex import TypeKind from clang.cindex import CursorKind from clang.cindex import Index #主要API from clang.cindex import Token from clang.cindex import TranslationUnit def GetTranslationUnit(filename): index = Index.create() tu = index.parse(filename,options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD) print("tTranslation Unit=%s"%(tu.spelling)) return tu def LoadLibClang(libclangPath): if Config.loaded == True: pass else: Config.set_library_file(libclangPath) def GetDefineStr(node): start_row=node.extent.start.line end_row = node.extent.end.line with open(node.location.file.name,encoding='utf-8',errors='ignore') as file: lines=file.readlines() retStr='' loop=start_row-1 while loop<end_row: retStr+=lines[loop] loop+=1 print(retStr,end='') #主函数 if __name__ == '__main__': filename='althttpd.c' # C语言文件 libclangPath = r'C:\Program Files\LLVM\bin\libclang.dll' #libclang库路径 LoadLibClang(libclangPath) #加载libclang库 tu=GetTranslationUnit(filename)#解析main.c ast_root_node=tu.cursor #获取cursor根节点 print(tu.spelling) functionList=[] print("Print all nodes in ast tree:") for node in ast_root_node.walk_preorder(): # 遍历词法分析结果 # if node.kind==CursorKind.MACRO_DEFINITION STRUCT_DECL TYPEDEF_DECL CALL_EXPR: if node.kind == CursorKind.MACRO_DEFINITION: if str(node.location.file) ==tu.spelling: GetDefineStr(node)
运行结果:
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:746 |
C语言训练-求具有abcd=(ab+cd)2性质的四位数 (C语言代码)浏览:626 |
C语言训练-角谷猜想 (C语言代码)浏览:1772 |
WU-蓝桥杯算法提高VIP-勾股数 (C++代码)浏览:1686 |
C语言程序设计教程(第三版)课后习题6.5 (C++代码)浏览:487 |
整除问题 (C语言代码)浏览:594 |
C语言程序设计教程(第三版)课后习题8.2 (C语言代码)浏览:1109 |
分解质因数 (C++代码)浏览:1561 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:501 |
C语言程序设计教程(第三版)课后习题8.8 (C语言代码)浏览:751 |