Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see a C/C++ source file after preprocessing in Visual Studio?

cl.exe, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++):

  • /E: preprocess to stdout (similar to GCC's -E option)
  • /P: preprocess to file
  • /EP: preprocess to stdout without #line directives

If you want to preprocess to a file without #line directives, combine the /P and /EP options.


Most compilers have an option to just run the preprocessor. e.g., gcc provides -E:

   -E  Stop after the preprocessing stage; do not run the compiler proper.  
       The output is in the form of preprocessed source code, which is sent
       to the standard output.

So you can just run:

gcc -E foo.c

If you can't find such an option, you can also just find the C preprocessor on your machine. It's usually called cpp and is probably already in your path. Invoke it like this:

cpp foo.c

If there are headers you need to include from other directories , you can pass -I/path/to/include/dir to either of these, just as you would with a regular compile.

For Windows, I'll leave it to other posters to provide answers as I'm no expert there.


Right-click on the file on the Solution Explorer, goto Properties. Under Configuration Properties->C/C++->Preprocessor, "Generate Preprocessed File" is what you are looking for. Then right-click on the file in the Solution Explorer and select "Compile". The preprocessed file is created in the output directory (e.g. Release, Debug) with an extension .i (thanks to Steed for his comment).


You typically need to do some postprocessing on the output of the preprocessor, otherwise all the macros just expand to one liners, which is hard to read and debug. For C code, something like the following would suffice:

gcc -E code.c | sed '/^\#/d' | indent -st -i2 > code-x.c

For C++ code, it's actually a lot harder. For GCC/g++, I found this Perl script useful.


Try cl /EP if you are using Microsoft's C++ compiler.


I don't know anything about Microsoft compiler, but on GCC you can use this:

gcc -E -P -o result.c my_file.h

If you want to see comments use this:

gcc -E -C -P -o result.c my_file.h

More options avaliable on this page.


In Visual Studio you can compile a file (or project) with /P.