【问题标题】:How can I compile C code that has already been C pre-processed with GCC?如何编译已经用 GCC 进行 C 预处理的 C 代码?
【发布时间】:2010-01-25 14:44:38
【问题描述】:

我正在 C 预处理和 C 编译之间执行一些源代码处理。目前我:

  1. gcc -E file.c > preprocessed_file.c.
  2. preprocessed_file.c做更多的事情。
  3. 使用preprocessed_file.c 继续编译。

如果您尝试编译 preprocessed_file.c,就像它是普通 C(第 3 步)一样,您会得到很多以下内容:

/usr/include/stdio.h:257: error: redefinition of parameter ‘restrict’
/usr/include/stdio.h:257: error: previous definition of ‘restrict’ was here
/usr/include/stdio.h:258: error: conflicting types for ‘restrict’
/usr/include/stdio.h:258: error: previous definition of ‘restrict’ was here
/usr/include/stdio.h:260: error: conflicting types for ‘restrict’
[...]

这只是在file.c 中使用#include <stdio.h>。幸运的是,有一个选项可以告诉 GCC 它正在通过将要编译的语言指定为 c-cpp-output(参见 this 页面上的 -x)来预处理已经预处理的 C 代码。但它不起作用。我只是得到这个:

$ gcc -x c-cpp-output -std=c99 bar.c
i686-apple-darwin9-gcc-4.0.1: language c-cpp-output not recognized
i686-apple-darwin9-gcc-4.0.1: language c-cpp-output not recognized
ld warning: in bar.c, file is not of required architecture
Undefined symbols:
  "_main", referenced from:
      start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

在新版本的 GCC 上的响应完全相同:

$ gcc-mp-4.4 -x c-cpp-output -std=c99 bar.c
[same error stuff comes here]

【问题讨论】:

    标签: c compilation


    【解决方案1】:

    看起来像是 GCC 文档中的拼写错误 - 请改用“-x cpp-output”。

    gcc -E helloworld.c > cppout
    gcc -x cpp-output cppout -o hw
    ./hw
    Hello, world!
    

    【讨论】:

    • 好吧,它适用于 hello world,但不适用于我的代码。让我看看发生了什么。
    • 也许试试 'gcc -x cpp-output -std=c99 xyz.cppoutput'?
    • Visual Studio 中是否有类似的选项?
    【解决方案2】:

    关于restrict 的警告是因为它是C99 中的关键字。因此,您必须使用相同的标准对代码进行预处理和编译。

    _main的错误是因为你的文件没有定义main()?执行以下操作应该可以:

    gcc -c -std=c99 bar.c
    

    它会创建bar.o。如果你的bar.c一个main()在里面定义,也许它不叫bar.c?例如,我使用有效的main() 创建了一个bar.c,然后:

    gcc -E -std=c99 bar.c >bar.E
    gcc -std=c99 bar.E
    

    得到:

    Undefined symbols:
      "_main", referenced from:
          start in crt1.10.6.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status
    

    在这种情况下,您需要-x c 选项:

    gcc -x c -std=c99 bar.E
    

    (或者,正如尼古拉所说,您需要将预处理文件保存到bar.i。)

    【讨论】:

      【解决方案3】:

      预处理后以.i后缀保存文件。 Gcc 手册页:

      文件.i 不应预处理的 C 源代码。 文件.ii 不应预处理的 C++ 源代码。

      【讨论】:

      • $ gcc -std=c99 bar.i 在来自 bar.h:4 的文件中,来自 bar.cex:4: /usr/include/stdio.h:327: error: 之前的语法错误'--' 令牌 /usr/include/stdio.h:335:错误:'__stdoutp'/usr/include/stdio.h:383 之前的语法错误:错误:'__sputc' 的静态声明遵循非静态声明 /usr /include/stdio.h:334: 错误:'__sputc' 的先前声明在这里
      • @Ollie:你是如何预处理文件的?你使用的命令是什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2014-09-09
      • 2011-10-22
      • 2010-11-14
      • 2011-06-03
      相关资源
      最近更新 更多