Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

python - How to automatically remove certain preprocessors directives and comments from a C header-file?

What's a good way to remove all text from a file which lies between /* */ and #if 0 and corresponding #endif? I want to strip these parts from C headers. This is the code I have so far:

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()  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use a regular expression to replace the parts of the file you don't want with the empty string (Note, this is very basic, it won't work e.g. for nested macros):

#!/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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...