【问题标题】:Find all macro definition in c header file在c头文件中查找所有宏定义
【发布时间】:2013-06-19 03:56:16
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • 在最简单的形式中你可以使用 grep 不是吗?确切的用例是什么?也就是说,当您说要列出所有宏定义时,您的意思是按照 CPP 的方式还是您只想列出它们?
  • 我知道 pycparser 使用 cpp 并且我设法在 c 文件中获取结构定义列表。但是我找不到在 h 文件中获取所有#define 宏的方法。现在,我只是用 python 解析头文件,但这不是我想要的。谢谢。

标签: c parsing pycparser


【解决方案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

希望对你有帮助

【讨论】:

  • 在解析完所有宏和包含后有没有办法查看文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2014-07-31
  • 2021-03-11
相关资源
最近更新 更多