c - 使用 Regex (POSIX) 在 #ifdef 语句外查找 printf() 调用

标签 c regex posix c-preprocessor

一位同事要求我想出一个正则表达式(POSIX 语法)来查找对 printf(...); 的调用——在 c 代码文件中-- 不在 #ifdef ... #endif 范围内。

不过,我在大学才刚学正则表达式,对它不是很有信心。

场景看起来像这样:

possibly some code
printf(some_parameters);  // This should match
possibly more code

#ifdef DEBUG
possibly some code
printf(some_parameters);  // This shouldn't match
possibly more code
#endif

possibly some code
printf(some_parameters);  // This should also match
possibly more code

请注意,c 文件可能根本不包含 #ifdef/#endif 语句,在这种情况下,对 printf(); 的所有调用都应该匹配。

到目前为止我试过的是:

(?<!(#ifdef [A-Å0-9]+)).*printf\(.*\);.*(?!(#endif))

...以及玩弄 .* 的位置(甚至包含/排除)

感谢任何帮助或提示。

最佳答案

正则表达式不是解决此问题的好方法。它们不能很好地处理多行搜索,并且它们在可以表达的模式方面受到限制,例如无法使用正则表达式指定任意嵌套。

解决此问题的正确方法是使用专为处理 C 代码中的条件编译指令而设计的工具。这将是编译器的 C 预处理器,或者像 unifdef 这样的专用工具:

$ unifdef -UDEBUG file.c | grep printf
printf(some_parameters);  // This should match
printf(some_parameters);  // This should also match

来自手册:

UNIFDEF(1)                BSD General Commands Manual               UNIFDEF(1)

NAME
     unifdef, unifdefall — remove preprocessor conditionals from code

SYNOPSIS
     unifdef [-ceklst] [-Ipath -Dsym[=val] -Usym -iDsym[=val] -iUsym] ... [file]
     unifdefall [-Ipath] ... file

DESCRIPTION
     The unifdef utility selectively processes conditional cpp(1) directives.
     It removes from a file both the directives and any additional text that
     they specify should be removed, while otherwise leaving the file alone.

     The unifdef utility acts on #if, #ifdef, #ifndef, #elif, #else, and #endif
     lines, and it understands only the commonly-used subset of the expression
     syntax for #if and #elif lines.  It handles integer values of symbols
     defined on the command line, the defined() operator applied to symbols
     defined or undefined on the command line, the operators !, <, >, <=, >=,
     ==, !=, &&, ||, and parenthesized expressions.  Anything that it does not
     understand is passed through unharmed.  It only processes #ifdef and
     #ifndef directives if the symbol is specified on the command line, other‐
     wise they are also passed through unchanged.  By default, it ignores #if
     and #elif lines with constant expressions, or they may be processed by
     specifying the -k flag on the command line.

关于c - 使用 Regex (POSIX) 在 #ifdef 语句外查找 printf() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12617667/

相关文章:

c - 一个文件上的 O_APPEND 标志使 read() 系统调用在其他文件上表现得很奇怪

python - 查找单词在字符串中的位置

正则表达式:如果一行不以特定字符串开头,请将其添加为前缀

c - 为什么这个基准代码使用如此高的 CPU?

linux - bash、ksh、tcsh 和 zsh 之间的区别

python - 如何编写一个正则表达式来匹配一个字符串文字,其中转义是引号字符的两倍?

c - 尝试实现一个从用户那里获取功能的通用链表

C:被 dup2() 困住了 :-(

C 读取不知道长度的一系列字符的最佳方法

我可以让 Unix 的 pthread.h 在 Windows 中编译吗?