How do I see a C/C++ source file after preprocessi

2018-12-31 06:16发布

Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?

10条回答
心情的温度
2楼-- · 2018-12-31 06:54

On Windows OS, a simple one line answer to this question is to use the below command in DOS prompt to see the preprocessed file:

CL /P /C myprogram.c

This will generate a file called myprogram.i. Open it and look out for your expanded preprocessors.

查看更多
墨雨无痕
3楼-- · 2018-12-31 06:55

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.

查看更多
君临天下
4楼-- · 2018-12-31 06:55

As bk1e and Andreas M. answered, the /P option for the compiler will cause it to preprocess a file. However, in my project using VS2005 and Platform Builder (for an embedded ARM processor), the project did not present an option in the dialog box (as described by Jim B) to enable that option.

I could run CL manually and add /P, but it failed because I did not know all of the appropriate command-line options that were invisibly being activated by Platform Builder during the full build. So I needed to know all of those options.

My solution was to go look in the build.log file, and find the line that executed

CL blah-blah-blah myfile.c

I copied this line to the clipboard. The "blah-blah-blah" part contained the build options, and was huge.

Back in the IDE, I right-clicked on myfile.c, chose "Open Build Window", and then in that window I pasted the build command-line, and added a "/P".

CL /P blah-blah-blah myfile.c

Done. The myfile.i file was produced, which contained the preprocessor output.

查看更多
美炸的是我
5楼-- · 2018-12-31 06:58

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.

查看更多
临风纵饮
6楼-- · 2018-12-31 07:02

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

查看更多
孤独总比滥情好
7楼-- · 2018-12-31 07:03

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).

查看更多
登录 后发表回答