Find all macro definition in c header file

孤街醉人 提交于 2021-01-29 08:30:12

问题


I am trying to get list of all macro definitions in a c header file by using pycparser.

Can you please help me on this issue with an example if possible?

Thanks.


回答1:


Try using pyparsing instead...

from pyparsing import *

# define the structure of a macro definition (the empty term is used 
# to advance to the next non-whitespace character)
macroDef = "#define" + Word(alphas+"_",alphanums+"_").setResultsName("macro") + \
            empty + restOfLine.setResultsName("value")
with open('myheader.h', 'r') as f:
    res = macroDef.scanString(f.read())
    print [tokens.macro for tokens, startPos, EndPos in res]

myheader.h looks like this:

#define MACRO1 42
#define lang_init ()  c_init()
#define min(X, Y)  ((X) < (Y) ? (X) : (Y))

output:

['MACRO1', 'lang_init', 'min']

The setResultsName allows you to call the portion you want as a member. So for your answer we did tokes.macro, but we could have just as easily accessed the value as well. I took part of this example from Paul McGuire's example here

You can learn more about pyparsing here

Hope this helps



来源:https://stackoverflow.com/questions/17182629/find-all-macro-definition-in-c-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!