How can I compile C code that has already been C pre-processed with GCC?

Ollie Saunders Source

I'm performing some source processing between C preprocessing and C compilation. At the moment I:

  1. gcc -E file.c > preprocessed_file.c.
  2. Do more stuff to preprocessed_file.c.
  3. Continue the compilation with preprocessed_file.c.

If you attempt to compile preprocessed_file.c as you would if it was normal C (step 3) you get lots of the following:

/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’
[...]

And that's just using #include <stdio.h> in file.c. Fortunately there's an option to tell GCC it's acting on C code that has already been preprocessed by specifying the language that is being compiled as c-cpp-output (see -x on this page). But it doesn't work. I just get this:

$ 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

And exactly the same response with a newer version of GCC:

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

Answers

answered 8 years ago Nikolai Fetissov #1

Save the file with the .i suffix after pre-processing. Gcc man page:

       file.i
           C source code which should not be preprocessed.

       file.ii
           C++ source code which should not be preprocessed.

answered 8 years ago Alok Singhal #2

The warnings about restrict are due to the fact that it is a keyword in C99. So, you have to pre-process and compile your code using the same standard.

The error about _main is because your file doesn't define main()? Doing the following should work:

gcc -c -std=c99 bar.c

and it will create bar.o. If your bar.c has a main() defined in it, maybe it is not called bar.c? For example, I created a bar.c with a valid main(), and did:

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

and got:

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

In that case, you need the -x c option:

gcc -x c -std=c99 bar.E

(Or, as Nikolai mentioned, you need to save the pre-processed file to bar.i.)

answered 8 years ago leegent #3

Looks like a typo in the GCC docs - try '-x cpp-output' instead.

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

comments powered by Disqus