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


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)

8

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