5

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

//

/*       
 */
Jens
  • 65,924
  • 14
  • 115
  • 171
Chiakey
  • 131
  • 3
  • 8
  • I would suggest [this](https://stackoverflow.com/a/53551634/3625404). (I wrote it to use inside vim.) – qeatzy Nov 30 '18 at 05:47

4 Answers4

4

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

Community
  • 1
  • 1
Jens
  • 65,924
  • 14
  • 115
  • 171
4

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.)
Community
  • 1
  • 1
Ingo Karkat
  • 161,022
  • 15
  • 231
  • 302
1
Esc:%s/\/\///

Esc:%s/\/\*//

Esc:%s/\*\///
Hema
  • 157
  • 3
  • 15
  • apart from what would your command do, you can use `#,@...` as separator for `:s`, if pattern contains `/` ... and your commands are not answers to this question. – Kent Apr 04 '14 at 09:30
  • What does this do to `printf ("//\n");`? – Jens Apr 04 '14 at 09:31
  • Jens... Yes... I agree that it will remove the // in printf statement too – Hema Apr 04 '14 at 09:46
0

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".

rici
  • 219,119
  • 25
  • 219
  • 314
boh717
  • 1,423
  • 2
  • 14
  • 23