C vs C++ – Why a C Executable is Smaller Compared to a C++ Executable

c

I'm trying to understand why the output file sizes are significantly different when using a C and a C++ compiler.

I was writing a small hello world program in C and C++, I noticed that in C version, the size of the executable was 93.7KB and in C++, the size of the same hello world program was 1.33MB. I am not sure why that is. I think it may be because C++ has more libraries and namespaces to use so I removed the using namespace std line and simply used std::cout and still the result was the same.

C

#include <stdio.h>

int main()
{
    printf("hello world");
    return 0;
}

// size 93.7KB

C++

#include <iostream>

int main()
{
    std::cout<<"Hello world";
    return 0;
}

// size 1.33MB

There doesn't seem to be much difference in the code above. Is there some sort of compiler difference that creates the differing file sizes?

Best Answer

Most of the C++ standard library, including all the streams which cout is part of, are inline template classes. Whenever you #include one of these inline library components, the compiler will copy and paste all that code to the source file that is including it. This will help the code to run faster, but will also add a lot of bytes to the final executable. This is likely the reason for the results you got.

Doing a similar test with the clang compiler on OSX (Apple LLVM version 5.1), using default flags, I got comparable results:

hello_cpp_cout:

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

Size: 14,924 bytes

hello_c:

#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}

Size: 8,456 bytes

And, as a bonus, I tried to compile a .cpp file with the exact same code as hello_c, i.e.: using printf instead of cout:

hello_cpp_printf:

#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}

Size: 8,464 bytes

As you can see, the executable size is hardly related to the language, but to the libraries you include in your project.

Update:

As it was noted by several comments and other replies, the choice of compiler flags will also be influential in the size of the compiled executable. A program compiled with debug flags will be a lot larger than one compiled with release flags, for example.

Related Topic