2013-06-19 30 views
0

我想通过使用pycparser来获取c头文件中所有宏定义的列表。查找c头文件中的所有宏定义

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

谢谢。

+1

在最简单的形式,你可以使用grep能不?什么是确切的用例?也就是说,当你说要列出所有的宏定义时,你的意思是CPP的方式是否意味着你只想列出它们? –

+0

我知道pycparser使用cpp,我设法得到c文件中的结构定义列表。但是我找不到在h文件中获取所有#define宏的方法。现在,我只是用python解析头文件,但这不是我想要的。谢谢。 – user1587140

回答

1

尝试使用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's example here

您可以了解更多关于pyparsing here

希望这有助于