Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove comments from C/C++ code

Tags:

c++

c

comments

Is there an easy way to remove comments from a C/C++ source file without doing any preprocessing. (ie, I think you can use gcc -E but this will expand macros.) I just want the source code with comments stripped, nothing else should be changed.

EDIT:

Preference towards an existing tool. I don't want to have to write this myself with regexes, I foresee too many surprises in the code.

like image 923
Mike Avatar asked Mar 06 '10 20:03

Mike


People also ask

How do you remove comments in C?

Remove comments in a string using C++ The string '\' denotes the line comment, which means the string next to it on the right will be ignored by the program. The string '\* and *\' is a multiline comment representing the string starting from '\* till the *\' will be ignored.

Do compilers remove comments?

A token can be an identifier, a literal value, a reserved word, or an operator. Comments and whitespace are mostly ignored during this phase. They are only used to separate different tokens. In the next steps, there is no concept for a comment or a whitespace, so yes, they are removed while compiling.

How do you write comments in C code?

Single-line comments start with two forward slashes ( // ). Any text between // and the end of the line is ignored by the compiler (will not be executed).


1 Answers

Run the following command on your source file:

gcc -fpreprocessed -dD -E test.c 

Thanks to KennyTM for finding the right flags. Here’s the result for completeness:

test.c:

#define foo bar foo foo foo #ifdef foo #undef foo #define foo baz #endif foo foo /* comments? comments. */ // c++ style comments 

gcc -fpreprocessed -dD -E test.c:

#define foo bar foo foo foo #ifdef foo #undef foo #define foo baz #endif foo foo 
like image 149
Josh Lee Avatar answered Sep 21 '22 01:09

Josh Lee