【问题标题】:How to automatically remove certain preprocessors directives and comments from a C header-file?如何从 C 头文件中自动删除某些预处理器指令和注释?
【发布时间】:2011-03-22 08:38:05
【问题描述】:

从位于/* */#if 0 以及相应的#endif 之间的文件中删除所有文本的好方法是什么?我想从 C 头文件中剥离这些部分。这是我到目前为止的代码:

For line in file:

    if def0Encountered == 0:  
        if Line.strip().startswith('#if 0') == True:  
            Def0StartsAt = Line.find('#if 0')  
            def0Encountered = 1  
            if Line.find('#endif')!= -1:  
                def0Encountered = 0  
                Def0EndsAt = Line.find('endif')  
                Line = Line[0:Def0StartsAt] + Line[Def0EndsAt + 2 : ]  
                List = Line.split()  

【问题讨论】:

标签: python string


【解决方案1】:

您可以使用正则表达式将您不想要的文件部分替换为空字符串(注意,这是非常基本的,例如对于嵌套宏不起作用):

#!/usr/bin/env python

import re

# uncomment/comment for test with a real file ...
# header = open('mycfile.c', 'r').read()
header = """

#if 0
    whatever(necessary)
    and maybe more

#endif

/* 
 * This is an original style comment
 *
 */

int main (int argc, char const *argv[])
{
    /* code */
    return 0;
}

"""

p_macro = re.compile("#if.*?#endif", re.DOTALL)
p_comment = re.compile("/\*.*?\*/", re.DOTALL)

# Example ...
# print re.sub(p_macro, '', header)
# print re.sub(p_comment, '', header)

【讨论】:

  • @miku:我不擅长正则表达式语法,但这是否涵盖了嵌套#ifs 的情况?
  • 谢谢,所以如果我同时使用 header= file.readlines 它将适用于整个 C 文件?
  • @Space:不,没有嵌套的#if。为此,您需要的不仅仅是常规语法/表达式。但好点,我会在我的帖子中添加一个注释。
  • @praveen:更新了我的帖子以包含文件处理。正如@Space 指出的那样,嵌套的#ifs 将无法与此版本正确匹配。
  • 为了使其完整,将输出转储到新文件中
【解决方案2】:

不确定这个奇怪的代码应该做什么,但可以直接逐行遍历文件。使用两个标志来检查您是否在评论内或是否在块内。根据字符串比较切换标志。根据两个标志的值,您要么输出当前行,要么忽略它....

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多