40

Is there an option that the GCC preprocessor could generate C source code and filter out irrelevant source code?

For example, a .c file has a #define switch to define for many different platforms. I'm only interested in one platform, and I want the C preprocessor to filter out unrelated code.

Does GCC support this?

3

4 Answers 4

41

Yes. Use the -E option:

gcc -E foo.c
Sign up to request clarification or add additional context in comments.

1 Comment

This has the side-effect of adding pre-processor line markers to the output which can cause problems if using the pre-processor as part of a custom (non-C?) pipeline! Add the -P option to prune these.
18

While the -E option will perform all pre-processing, it also produces some very 'raw' output that might not be what you want (depending on what you want).

If you need to debug a macro expansion that's not doing what you expect, E is a good way to go. If you simply want to filter out the 'inactive code', but leave the remaining code in more-or-less original form, you might want to look at the answers to the following Stack Overflow question:

Comments

5

It sounds like you want unifdef, not the GCC preprocessor.

1 Comment

0

For completeness sake: If you are interested in running just the preprocessor, you can also use cpp:

cpp foo.c

See https://gcc.gnu.org/onlinedocs/cpp/Invocation.html for reference:

Most often when you use the C preprocessor you do not have to invoke it explicitly: the C compiler does so automatically. However, the preprocessor is sometimes useful on its own. You can invoke the preprocessor either with the cpp command, or via gcc -E. In GCC, the preprocessor is actually integrated with the compiler rather than a separate program, and both of these commands invoke GCC and tell it to stop after the preprocessing phase.

The cpp command expects two file names as arguments, infile and outfile. The preprocessor reads infile together with any other files it specifies with ‘#include’. All the output generated by the combined input files is written in outfile.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.