7

Are there tools to transform source code in C++ to the source code in C/C++, but with instantiated (unrolled) templates? This is necessary for an unambiguous understanding, into the what code C++ templates converted. May be it is present in the IDEs(MSVS, QtCreator, ...) or in the compilers(ICC, GCC, MSVC, Clang)?

Alex
  • 12,578
  • 15
  • 99
  • 195
  • I remember one time when I ended up compiling heavily templated C++ code into assembly because the number of classes, templates and files was unreasonably high to dive into to find out what I needed. Of course, this won't work in every case. – Alexey Frunze Mar 31 '13 at 13:15
  • @Alexey Frunze So, I can see only the assembly code, but not C/C++-code after instantiation of the templates, is this true? – Alex Apr 01 '13 at 08:49
  • Yes and no. If you're interested to find out what the code does exactly behind all those layers of abstractions, you will. And you'll see what functions get called and what types are used. So, even though some information present in the source code gets lost, you can still see quite a lot. You may be interested in enabling and disabling code optimization, though. With too heavy optimization you may get a lot of functions inlined and so the code structure won't be as apparent. – Alexey Frunze Apr 01 '13 at 08:57

2 Answers2

6

This seems already answered on SO

The Idea/principle from Alexey Frunze to use the disassembled code is quite good, together with the use of simplified templates there is a pretty good chance to understand exactly what it does.

Edit 1 There are a few other possibilities on how to get an understanding of the things which the compiler had done

  1. Use: gcc -S -O1 {yourcode.cpp} to get the assembly and use the tool c++filt (its a part of binutils to convert the disassembly to C-Code if you feel more comfortable with C-Code
  2. Use: g++ -fdump-tree-original file.cpp to get some (pseudo) C++ code
  3. Use the MSVC++ debugger with the breakpoint after the last instantiation and see all types and values which are the parameters of the instantiated template
  4. Use: GCC XML for generating XML with instantiated templates (FAQ)
  5. To know how the compiler instantiated and optimized the templates you can use Clang: -emit-llvm to get the LLVM IR, and use llvm-dis to convert it to text
  6. CPP insights is a website of a LLVM based tool to see instantiations
Quonux
  • 2,975
  • 1
  • 24
  • 32
  • Comeau C++ can "compile" C++ to C code, but the compiler isn't maintained anymore and it's not available for download. – Quonux Nov 18 '20 at 12:16
2

You could work around the problem by placing a deliberate error inside the instantiation or its parameters, then you'd have the compiler (assuming decent versions: gcc 4.8, clang, etc) output something along the lines of: "error with template XXX instantiated with A=int, B=float, ..".

rmn
  • 2,386
  • 1
  • 14
  • 21