如何从C源文件中删除所有/**/注释?

Vij*_*jay 14 regex unix perl awk sed

我有一个C文件,我从其他地方复制,但它有很多评论如下:

int matrix[20];
/* generate data */
for (index = 0 ;index < 20; index++)
matrix[index] = index + 1;
/* print original data */
for (index = 0; index < 5 ;index++)
Run Code Online (Sandbox Code Playgroud)

如何删除/* 和所包含的所有注释*/.有时,评论由4-5行组成,我需要删除所有这些行.

基本上,我需要删除之间的所有文字/**/甚至\n能之间进入.请帮助我使用其中一个sed,awkperl.

ezp*_*zpz 32

为什么不使用c预处理器来做到这一点?你为什么要把自己限制在一个本土的正则表达式?

[编辑]这种方法也可以printf(".../*...")干净地处理Barts 场景

例:

[File: t.c]
/* This is a comment */
int main () {
    /* 
     * This
     * is 
     * a
     * multiline
     * comment
     */
    int f = 42;
    /*
     * More comments
     */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

.

$ cpp -P t.c
int main () {







    int f = 42;



    return 0;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以删除空格并压缩所有内容

$ cpp -P t.c | egrep -v "^[ \t]*$"
int main () {
    int f = 42;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

没有用重新发明轮子,有吗?

[编辑]如果你想通过这种方式扩大包含的文件和macroa,cpp提供标志这一点.考虑:

[档案:tc]

#include <stdio.h>
int main () {
    int f = 42;
    printf("   /*  ");
    printf("   */  ");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

.

$ cpp -P -fpreprocessed t.c | grep -v "^[ \t]*$"
#include <stdio.h>
int main () {
    int f = 42;
    printf("   /*  ");
    printf("   */  ");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在宏扩展轻微警告是可以避免的,但宏观的原始定义从源剥离.

  • 预处理器有一个(可能是不可取的)"副作用":它还处理宏,包括包含的文件,等等...... (4认同)
  • 您可以通过`-fpreprocessed`摆脱宏扩展.我会更新提到这一点 (4认同)

Bri*_*new 12

perlfaq6.这是一个非常复杂的场景.

$/ = undef;
$_ = <>;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
print;
Run Code Online (Sandbox Code Playgroud)

一句警告 - 一旦你完成了这个,你有一个测试场景向自己证明你刚刚删除了评论而没有任何价值吗?如果你正在运行如此强大的正则表达式,我会确保进行某种测试(即使你只是记录之前/之后的行为).


Sin*_*nür 6

看一下strip_commentsInline :: Filters中的例程:

sub strip_comments {
    my ($txt, $opn, $cls, @quotes) = @_;
    my $i = -1;
    while (++$i < length $txt) {
    my $closer;
        if (grep {my $r=substr($txt,$i,length($_)) eq $_; $closer=$_ if $r; $r}
        @quotes) {
        $i = skip_quoted($txt, $i, $closer);
        next;
        }
        if (substr($txt, $i, length($opn)) eq $opn) {
        my $e = index($txt, $cls, $i) + length($cls);
        substr($txt, $i, $e-$i) =~ s/[^\n]/ /g;
        $i--;
        next;
        }
    }
    return $txt;
}
Run Code Online (Sandbox Code Playgroud)


Sin*_*nür 5

cpp除非您了解其后果,否则请不要使用此项:

$ cat t.c
#include <stdio.h>

#define MSG "Hello World"

int main(void) {
    /* ANNOY: print MSG using the puts function */
    puts(MSG);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在,让我们来看看cpp:

$ cpp -P t.c -fpreprocessed


#include <stdio.h>



int main(void) {


    puts(MSG);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

显然,这个文件不再编译.