且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-29 23:13:49

为什么不直接使用C preprocessor做到这一点?你为什么要限制自己一个土生土长的正则表达式?

Why not just use the c preprocessor to do this? Why are you confining yourself to a home-grown regex?

这种方法还可以处理的Barts 的printf(... / * ...)情景干净

This approach also handles Barts printf(".../*...") scenario cleanly

例如:

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

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







    int f = 42;



    return 0;
}

或者,您可以删除空格和凝聚一切

Or you can remove the whitespace and condense everything

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

没有使用重新发明***,有没有?

No use re-inventing the wheel, is there?


如果你想的的通过这种方式扩大包含的文件和macroa, CPP 提供标志这一点。试想一下:

If you want to not expand included files and macroa by this approach, cpp provides flags for this. Consider:

[文件:T.C]

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

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

的可避免在宏扩展轻微的警告,但宏的原始定义是从源头上剥离。

There is a slight caveat in that macro expansion can be avoided, but the original definition of the macro is stripped from the source.