c - 仅运行预处理器但仅针对某些语句

标签 c gcc c-preprocessor

我在程序中定义了许多调试语句,我希望能够在没有这些语句的情况下制作源代码的副本。

为了做到这一点,我首先查看了 GCC 的 -E 命令行参数,它只运行预处理器,但是这远远超出了我的预期,扩展了包含的文件并添加了#line 语句。

例如:

#include <stdio.h>

#ifdef DEBUG
    #define debug( s ) puts ( s );
#else
    #define debug( s )
#endif

int main( int argc, char* argv[] )
{
    debug( "Foo" )

    puts( "Hello, World!" );

    return 0;
}

我希望将其处理为:

#include <stdio.h>

int main( int argc, char* argv[] )
{


    puts( "Hello, World!" );

    return 0;
}

然后我可以用 astyle 之类的东西整理它,不需要手动工作就可以得到我想要的东西。

是否有我缺少的 GCC 指令或是否有能够执行此操作的工具?

最佳答案

如果-E没有帮助,然后尝试使用 -fdump-tree-all如果你没有看到你想要的东西,那就是 GCC 不可用(或)不提供.

OTOH,这个问题已经在 SO 中讨论如下,请引用下面的内容以获得一些想法。

  1. Can gcc output C code after preprocessing?
  2. How do I see a C/C++ source file after preprocessing in Visual Studio?

希望对您有所帮助!


嗨,马特,

我看到了你对@nos 的评论。但我手头有一个这样的脚本,所以与你分享。您可以尝试阅读我对类似问题的回答 here

将以下代码复制到一个文件中,比如 convert.sh .为该文件分配执行权限,chmod +x convert.sh并按如下方式运行:

$./convert.sh <filename>.c
$cat filename.c.done

<filename>.c.done会有你需要的!

#!/bin/bash

if [[ $# -ne 1 || ! -f $1 ]] ; then
    echo "Invalid args / Check file "
    exit 
fi

file_name=$1

grep '^\s*#\s*include' $file_name > /tmp/include.c
grep -Pv '^\s*#\s*include\b' $file_name > /tmp/code.c
gcc -E /tmp/code.c | grep -v ^# > /tmp/preprocessed.c
cat /tmp/include.c > $file_name.done
cat /tmp/preprocessed.c >> $file_name.done

希望这对您有所帮助!

关于c - 仅运行预处理器但仅针对某些语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713336/

相关文章:

c - C 中的二维数组排序

c -\b 是如何实现的?

c - OpenCV 2.1 Mac OSX 上简单视频流的内存泄漏

c - 使用 GTK+2 时收到 “format not a string literal and no format arguments” 警告

c++ - GCC 的 std::sort 与 lambda 的不稳定行为

c++ - 是否可以定义另一个预处理器指令?

不透明结构的 C typedef 编码风格

c - 某些 GCC 编译器如何修改常量 char 指针?

c++ - #define 与 const 声明的优先级

c - 如何在 C 中实现动态调度表