views:

641

answers:

5

I learned that compiler will expand macros while compiling. Templates are also expanded at the compile time. Is there any way to see this expanded code? I am compiling using Visual Studio 2008.

any thoughts?

+6  A: 

The VC++ compiler (cl.exe) supports a few command line switches for this:

/E preprocess to stdout
/P preprocess to file
/EP preproscess to stdout with no #lines

Additional command-line switches can be added in your project properties. In my version (VC2005), Configuration Options -> C/C++ -> Command Line -> Additional Options

Dave Ray
+2  A: 

To emit the preprocessed code, call cpp directly of use the -E option in gcc and related compilers; I'm sure other compilers or suites have similar things (indeed as per the other answer it's /E or /P in VC++).

Not sure about outputting instantiated templates. That's much harder to do, I think, since it's actually part of compilation rather than preprocessing (at least in modern compilers, since the original cfront version which was a c++-to-c translator, if I recall correctly).

Andrew Jaffe
+4  A: 

The compiler doesn't actually do any of the macro expansion. That is the task of the pre-processor. It all appears as one step, but the compiler actually forks out to a separate pre-processor tasks and traps the output for you.

Templates are not "expanded" at compile time. They are instantiated on use during compile. The difference is that the compiler immediately generates object code for the template; there's no intermediate source code that comes out. You can't look at the instantiated template code as source, it's dumped out as assembly when it's needed.

If you have GCC you can also call the pre-processor directly using 'cpp' with the right arguments (mostly include paths and command line macro definitions). Others have answered for MSVC.

Adam Hawes
Instantiated during compiling, _or linking_ (if you (can) use export)
MSalters
It depends on the compiler - the pre-processor runs as if in a separate stage, but it is not mandatory that it is a separate program.
Jonathan Leffler
+1  A: 

Note that /E in VC++ only expands preprocessor statements (that is, #include, #ifdef, #define etc.)

I am not aware of any modern compiler that allows to expand templates.

peterchen
A: 

It's easy to add an option to compilers to show the output after macro substitution. That's defined as a simple text substitution option anyway. Many compilers implement this as a separate stage, sometimes even handled as a separate tool. In any case, the result of the macro substitution is a collection of Translation Units in text form.

Templates, on the other hand, are compiled. There are multiple stages to this. Names are resolved twice, for instance. In either stage, the compiler would store the result of the name lookup. That's a table entry. How would you show that in text form? There's no trivial C++ expression for that.

MSalters