如何编译已经使用GCC进行C预处理的C代码?
我正在C预处理和C编译之间执行一些源处理。 目前我:
-
gcc -E file.c > preprocessed_file.c
。 - 为
preprocessed_file.c
做更多的事情。 - 使用
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
。 幸运的是,有一个选项告诉GCC它通过指定编译为c-cpp-output
的语言来处理已经预处理的C代码(参见本页的-x
)。 但它不起作用。 我得到这个:
$ 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]
看起来像是GCC文档中的拼写错误 – 请尝试’-x cpp-output’。
gcc -E helloworld.c > cppout gcc -x cpp-output cppout -o hw ./hw Hello, world!
有关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
在这种情况下,您需要-xc
选项:
gcc -xc -std=c99 bar.E
(或者,正如Nikolai所提到的,您需要将预处理的文件保存到bar.i
)
预处理后使用.i
后缀保存文件。 Gcc手册页:
file.i 不应预处理的C源代码。 file.ii 不应预处理的C ++源代码。