Include of iostream leads to different binary

  • A+

Compiling the following code

int main() {     return 0; } 

gives the assembly

main:         xorl    %eax, %eax         ret 

If now iostream is included

#include <iostream>    int main(){     return 0; } 

this assembly is created.

main:         xorl    %eax, %eax         ret _GLOBAL__sub_I_main:         subq    $8, %rsp         movl    $_ZStL8__ioinit, %edi         call    std::ios_base::Init::Init() [complete object constructor]         movl    $__dso_handle, %edx         movl    $_ZStL8__ioinit, %esi         movl    $_ZNSt8ios_base4InitD1Ev, %edi         addq    $8, %rsp         jmp     __cxa_atexit 

Full optimization is turned on (-O3).

Can someone explain, why including an unused header changes the binary. What is _GLOBAL__sub_I_main:?


Including the iostream header has the effect of adding the definition of a static std::ios_base::Init object. The constructor of this static object initializes the standard stream objects std::cout, std::cerr and so forth.

The reason it's done is to avoid the static initialization order fiasco. It ensures the stream objects are properly initialized across translation units.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: