Chiakey
Chiakey

Reputation: 131

In vim, how to remove all the C and C++ comments?

How to remove all C and C++ comments in vi?

//

/*       
 */

Upvotes: 5

Views: 4707

Answers (4)

Alberto Coletta
Alberto Coletta

Reputation: 1603

You can use a lexical analyzer like Flex directly applied to source codes. In its manual you can find "How can I match C-style comments?".

If you need an in-depth tutorial, you can find it here; under "Lexical Analysis" section you can find a pdf that introduce you to the tool and an archive with some practical examples, including "c99-comment-eater".

Upvotes: 0

Ingo Karkat
Ingo Karkat

Reputation: 172540

With regular expressions, because of the complexity of C/C++ syntax, you will at best achieve a solution that is 90% correct. Better let the right tool (a compiler) do the job.

Fortunately, Vim integrates nicely with external tools. Based on this answer, you can do:

:%! gcc -fpreprocessed -dD -E "%" 2>/dev/null

Caveats:

  • requires gcc
  • it also slightly modifies the formatting (shrunk indent etc.)

Upvotes: 4

Jens
Jens

Reputation: 72639

You can't. Parsing C and C++ comments is not something that regular expressions can do. It might work for simple cases, but you never know if the result leaves you with a corrupted source file. E.g. what happens to this:

 printf ("//\n");

The proper way is to use an external tool able to parse C. For example some compilers may have an option to strip comments.

Writing a comment stripper is also a basic exercise in lex and yacc programming.

See also this question: Remove comments from C/C++ code

Upvotes: 4

Hema
Hema

Reputation: 167

Esc:%s/\/\///

Esc:%s/\/\*//

Esc:%s/\*\///

Upvotes: 1

Related Questions