2

Can someone explain me why a simple C++ application -

#include <iostream>
int main()
{
    std::cout << "Hello world!";
    return 0;
}

compiled with MSVC 2012 looks very weird in IDA / Olly? Why I see hundreds of lines of ASM code instead of the few I expected? Can someone explain to me where all that code comes from? Thanks.

2
  • 2
    1. standard entry/exit code, 2. libraries, 3. 1 line of C++ is only very rarely translated to 1 line of assembly. How "few" did you actually expect?
    – Jongware
    Feb 16, 2014 at 23:41
  • If you don't make any C++ library function calls (for example, if you only use Windows API functions) then you can configure the MSVC 2012 linker to use main() as the entry point. This will remove all extraneous ASM code from the linked executable. Feb 17, 2014 at 17:52

2 Answers 2

5

One piece of code you use is #include this includes: http://www.opensource.apple.com/source/gcc/gcc-937.2/libio/iostream.h

You might spot the Class. This generates a lot of code, also you need to think about libs, default compiler generated code etc etc.

If you assemble a basic application with NASM you will also spot more Assembly than you wrote.

4

There are several reasons for that:

  • Compiler itself - you will get slightly different code while using different compilers due to optimizations compiler implements, its default options.
  • to actually run your code, compiler will insert bootstrap code for, processing possible command line commands, security protections that are common today, language specifics support:
    • buffer overflow - stack cookies
    • UAC protections
    • RTTI - real time type information, C++ thing
    • and there are others too.
  • Another thing, is compiler optimizations which in most cases will make the code you wrote, look completely different. In some cases, compiler can event remove you code at all - you will get an "empty" executable :-)

I hope that you understand, that to add all the above, compiler needs to add some code and this is even before your code is there. Of course, you can disable all of the above by playing with the parameters.

Reducing Executable Size is a pretty good list of useful info which can help you to understand what is going on under the hood.

My suggestion is to write the following code

int main()
{
   return 0;
}

remove all optimizations and start your study from there by adding/removing compiler options one in a time.

Have Fun!

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.