Search code examples
c++cgcciostreamstdio

how does the size of compiled binaries depend on the used libraries? c/c++


Last week I found a simple game on the web called killallcops.exe. I studied the binaries and wondered why the programm is that big. (About 460k)

So I rewrote the game using iostream

#include <iostream>
int main(){
    std::cout << "All cops are killed.\nCongratulations";
    std::cin.ignore();
    return 0;
}

compiled it with g++ and got 460k too.

I really wondered why this thing was so big and rewrote it using stdio

#include <stdio.h>
int main(){
    printf("All cops are killed.\nCongratulations");
    while(getchar() != '\n'){}
    return 0;
}

compiled it with gcc and got 13k.

I know that iostream has much more abilities than stdio (like typesafety) and thus is itself much bigger, but why does this result in bigger binaries and are there solutions to reduce the size when using iostream, for example only using specific parts of it?

edit: as stated below using gcc 3.4.4 under cygwin


Solution

  • I'll flesh out my comment as an answer:

    <iostream> has a lot of internal dependencies, even for using a simple cout call. It brings in a lot of other code/headers it needs to work (which includes template code and such). Up front let's say the size of bringing in <iostream> is probably not very significant in a nontrivial application.

    You can trust the compiler/linker to know what they're doing, but if you want to reduce the binary size, try using options like gcc -s, which strips symbols, or flags like -Os which attempts to optimize the binary for size.

    I suspect a lot of your binary size problems actually comes from something else: a statically-linked libstdc++.

    If you're using MinGW on Windows, do note that until very recently, their implementation of the GCC toolchain did not have a dynamically-linked libstdc++; instead all C++ builds statically link in libstdc++ which will greatly increase the size of your binaries.

    Here's a comparison, the size of a binary produced by g++ for your code, on Linux, using GCC 4.6.1. No optimization or symbol stripping was performed on these builds.

    λ > ls -lh a.out          
    -rwxr-xr-x 1 billylee billylee 6.1K Dec 24 10:37 a.out
    

    And here's one produced by GCC

    λ > ls -lh trial
    -rwxr-xr-x 1 billylee billylee 4.9K Dec 24 10:41 trial
    

    The g++ version is a little larger than the gcc version, but not 100x larger.

    edit: If you're using MinGW - there's a recent thread here: How to reduce the size of executable produced by MinGW g++ compiler?

    MinGW gcc 4.5.0+ should use dynamic linking by default, check your version if you are using MinGW.