Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 pythonimport 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)

Solution 2:

Not sure what this strange code should be doing but it is straight forward to iterate over the file line-by-line. Use two flags to check if you are inside a comment or and if block. Toggle the the flags based on string comparisions. Based on the value of both flags you either output the current line or ignore it....

Post a Comment for "How To Automatically Remove Certain Preprocessors Directives And Comments From A C Header-file?"