Delete comments from a C/C++ source file

Sunday, December 30, 2012 , 0 Comments

Solution can be many but below is a good one:
cpp -P -fpreprocessed t.c | grep -v "^[ \t]*$"
another is a complex one . For example, this one-liner
perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
will work in many but not all cases. You see, it's too simple-minded for certain kinds of C programs, in particular, those with what appear to be comments in quoted strings. For that, you'd need something like this, created by Jeffrey Friedl and later modified by Fred Curtis.
$/ = undef;
$_ = <>;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
Reference for this is taken from perlfaq6