0

我正在尝试使用 pycparser 获取 ac 头文件中所有宏定义的列表。

如果可能的话,你能帮我解决这个问题吗?

谢谢。

4

1 回答 1

2

尝试使用 pyparsing 代替...

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 看起来像这样:

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

输出:

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

setResultsName 允许您调用您想要作为成员的部分。因此,对于您的答案,我们使用了 tokes.macro,但我们也可以轻松访问该值。我从Paul McGuire 的示例中获取了这个示例的一部分

您可以在此处了解有关pyparsing 的更多信息

希望这可以帮助

于 2013-07-03T22:21:04.817 回答