c++ - 从源代码中删除 C++ 注释

标签 c++ regex comments

我有一些带有 /* */// 样式注释的 C++ 代码。我想有一种方法可以自动将它们全部删除。显然,使用带有一些正则表达式搜索 /**/// 的编辑器(例如 ultraedit)应该可以完成这项工作。但是,仔细观察,完整的解决方案并不是那么简单,因为序列/* 或//如果它们在另一个注释、字符串文字或字 rune 字中,则可能不代表注释。例如

printf(" \" \" " "  /* this is not a comment and is surrounded by an unknown number of double-quotes */");

是双引号内的注释序列。而且,确定一个字符串是否在一对有效的双引号内也不是一项简单的任务。虽然这

// this is a single line comment /* <--- this does not start a comment block 
// this is a second comment line with an */ within

是其他评论中的评论序列。

考虑到字符串文字和注释,是否有更全面的方法从 C++ 源代码中删除注释?例如,我们可以指示预处理器在不执行 #include 指令时删除注释吗?

最佳答案

C 预处理器可以删除注释。

编辑:

我已经更新,以便我们可以使用 MACROS 来扩展 #if 语句

> cat t.cpp
/*
 * Normal comment
 */
// this is a single line comment /* <--- this does not start a comment block 
// this is a second comment line with an */ within
#include <stdio.h>

#if __SIZEOF_LONG__ == 4
int bits = 32;
#else
int bits = 16;
#endif

int main()
{
    printf(" \" \" " " /* this is not a comment and is surrounded by an unknown number of double-quotes */");
    /*
     * comment with a single // line comment enbedded.
     */
    int x;
    // A single line comment /* Normal enbedded */ Comment
}

因为我们希望 #if 语句正确展开,所以我们需要一个定义列表。
这是相对微不足道的。 cpp -E -dM

然后我们通过预处理器将#defines 和原始文件通过管道返回,但这次阻止包含被扩展。

> cpp -E -dM t.cpp > /tmp/def
> cat /tmp/def t.cpp | sed -e s/^#inc/-#inc/ | cpp - | sed s/^-#inc/#inc/
# 1 "t.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "t.cpp"






#include <stdio.h>


int bits = 32;




int main()
{
    printf(" \" \" " " /* this is not a comment and is surrounded by an unknown number of double-quotes */");    



    int x;

}

关于c++ - 从源代码中删除 C++ 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4410532/

相关文章:

在 h 文件中声明的 c++ 静态数组给出警告 'defined but not used'

c++ - Boost.Spirit 与 Boost.Variant 和 C++11 : Expecting a zero-argument constructor

c++ - 由非常量变量定义的大小数组

php - 正则表达式(preg_match)匹配任何东西

javascript - 正则表达式:向前查找仅获取第一次出现

mysql - 如何使用键盘快捷键或菜单项注释 MySQL Workbench 中的代码?

c++ - 如何检索在单独线程上运行的函数的 move 指针?

regex - 使用任何扩展名重命名 perl 文件

sql - 新手问题 : Code line ends with column name null. 如何在本行末尾添加注释?

emacs - 如何为主要模式定义注释语法?