Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run the GCC preprocessor to get the code after macros like #define are expanded?

Tags:

gcc

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?

like image 652
Richard Luo Avatar asked Oct 12 '10 16:10

Richard Luo


People also ask

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

How do I run a C preprocessor?

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.

What is a gcc preprocessor?

The C preprocessor implements the macro language used to transform C, C++, and Objective-C programs before they are compiled. It can also be useful on its own.

What is macro processing in preprocessor?

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.


2 Answers

Yes. Use the -E option:

gcc -E foo.c 
like image 127
JesperE Avatar answered Sep 30 '22 09:09

JesperE


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:

  • Is there a C pre-processor which eliminates #ifdef blocks based on values defined/undefined?
like image 23
Michael Burr Avatar answered Sep 30 '22 10:09

Michael Burr