环境: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语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复